How to get the last part of a string in JavaScript?
My url will look like this:
http://www.example.com/category/action
How can I get the word "action". This last part of the url (after the last forward slash "/") will be different each time. So whether its "action" or "adventure", etc. how can I always get the word after the last closing forward slash?
One way:
var lastPart = url.split("/").pop();
Assuming there is no trailing slash, you could get it like this:
var url = "http://www.mysite.com/category/action";
var parts = url.split("/");
alert(parts[parts.length-1]);
However, if there can be a trailing slash, you could use the following:
var url = "http://www.mysite.com/category/action/";
var parts = url.split("/");
if (parts[parts.length-1].length==0){
alert(parts[parts.length-2]);
}else{
alert(parts[parts.length-1]);
}
str.substring(str.lastIndexOf("/") + 1)
Though if your URL could contain a query or fragment, you might want to do
var end = str.lastIndexOf("#");
if (end >= 0) { str = str.substring(0, end); }
end = str.lastIndexOf("?");
if (end >= 0) { str = str.substring(0, end); }
first to make sure you have a URL with the path at the end.