Get last value in URL path string
11,470
Solution 1
you can try this:
s="http://localhost:8888/#!/path/somevalue/needthis"
var final = s.substr(s.lastIndexOf('/') + 1);
alert(final)
Solution 2
window.location.pathname.split("/").pop()
Solution 3
what I would do is make a function that takes an index of what part you want.. that way you can get any part anytime
getPathPart = function(index){
if (index === undefined)
index = 0;
var path = window.location.pathname,
parts = path.split('/');
if (parts && parts.length > 1)
parts = (parts || []).splice(1);
return parts.length > index ? parts[index] : null;
}
with this you can of course make changes like a getLastIndex flag that when true you can return that..
getPathPart = function(index, getLastIndex){
if (index === undefined)
index = 0;
var path = window.location.pathname,
parts = path.split('/');
if (parts && parts.length > 1)
parts = (parts || []).splice(1);
if(getLastIndex){
return parts[parts.length - 1]
}
return parts.length > index ? parts[index] : null;
}
Solution 4
Since you are using angularjs, you can use:
$location.path().split('/').pop();
Author by
user3871
Updated on June 14, 2022Comments
-
user3871 almost 2 years
Given an href like:
http://localhost:8888/#!/path/somevalue/needthis
How can I get the last value in the path string (aka: "needthis")?
I tried using
window.location.pathname
, which gives "/".I also tried using Angular's
$location
, which doesn't provide the last value.