I have a couple of URL's that I need to obtain a specific part of the last part of the URI
If I have the url www.test.co/index.php/government-printer-sales.html
I only need to obtain government
from the URL. All url's a开发者_高级运维re in the same structure so if I have www.test.co/index.php/management-fees.html
I need to obtain the word management
I tried the following
var str = document.URL.split('/');
var type = str[5].split('-',1);
which gives me some result, but I'm sure there is a better way. If there's anyway I can obtain this from eiter mootools or just plain javascript
You could use a regular expression to pull out the string after the last slash and before the first dash:
var regex = /\/([^/\-]+)[^/]*$/;
var matches = regex.exec('www.test.co/index.php/government-printer-sales.html');
var type = matches[1]; // government
You can look here and then here and then check this code:
var myString = "www.test.co/index.php/government-printer-sales.html";
var myRegexp = /(www.test.co\/index.php\/)(\w+)-(.)*/g;
var match = myRegexp.exec(myString);
alert(match);
Splice is a great function passing in a negative number as the first argument will create a new array with elements counting from the end of the array.
document.URL
> "http://stackoverflow.com/questions/7671441/getting-a-specific-part-of-a-url-using-javascript"
document.URL.split('/').splice(-1)[0].split('-')[0]
> "getting"
This is similar to python's list splicing lst[:-1]
Try this:
var type = window.location.pathname.match(/index.php\/([^-]+)(?:-)/)[1];
It searches for any characters following index.php/
excluding a hyphen, but followed by a single hyphen and fetches the value in between.
精彩评论