How to get the last part of a string in JavaScript?

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

One way:

var lastPart = url.split("/").pop();

Solution 2 - Javascript

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]);  
}

Solution 3 - Javascript

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.

Solution 4 - Javascript

Or the regex way:

var lastPart = url.replace(/.*\//, ""); //tested in FF 3

OR

var lastPart = url.match(/[^/]*$/)[0]; //tested in FF 3

Solution 5 - Javascript

Check out the split method, it does what you want: http://www.w3schools.com/jsref/jsref_split.asp

Solution 6 - Javascript

Well, the first thing I can think of is using the split function.

string.split(separator, limit)

Since everyone suggested the split function, a second way wood be this:

var c = "http://www.example.com/category/action";
var l = c.match(/\w+/g)
alert(l)

The regexp is just a stub to get the idea. Basically you get every words in the url.

l = http,www,example,com,category,action

get the last one.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJacobView Question on Stackoverflow
Solution 1 - JavascriptAtes GoralView Answer on Stackoverflow
Solution 2 - JavascriptNiklasView Answer on Stackoverflow
Solution 3 - JavascriptMike SamuelView Answer on Stackoverflow
Solution 4 - JavascriptJonathonView Answer on Stackoverflow
Solution 5 - JavascriptpfhayesView Answer on Stackoverflow
Solution 6 - JavascriptdierreView Answer on Stackoverflow