You can accomplish this fairly quickly:
//var url = (document.URL);
var url = ('http://www.example.com/example');
var index = url.substr(url.lastIndexOf('/')+1);
Here is a jsFiddle to play with.
The code above uses document.URL
to get the full URL of the current document.
Then substr
starting at one more than the last index of /
. This will leave you with everything after the last /
.
However, if your URL looked like "http://www.example.com/example/" this would return nothing, an empty string. You'd have to do some additional work to account for that. This is why some examples would use .split()
since you can then split the URL at every /
and grab the item from an array.
In the spirit of providing not just an answer but the right one, I think a regular expression and .match()
is the right way to go. This solution comes from a very similar question on StackOverflow.
var url = ('http://www.example.com/example/test/example2/');
var index = url.match(/\/([^\/]+)\/?$/)[1];
This will give you example2
regardless of a whether or not a trailing slash exists.
Here is a jsFiddle.