68

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?

1

6 Answers 6

200

One way:

var lastPart = url.split("/").pop();
3
  • 1
    in case the url has a trailing slash (i.e., http://www.example.com/category/action/), we can apply a filter empty parts: var lastPart = url.split('/').filter(e => e).pop(). Also, I prefer to use slice(-1) instead of pop() to return the last part because pop() returns undefined while slice(-1) will return empty array. So I would do: var lastPart = url.split('/').filter(e => e).slice(-1)
    – kimbaudi
    Jun 17, 2019 at 0:03
  • @kimbaudi Can you please give an example where slice(-1) is preferrable over pop().
    – Timo
    Mar 18 at 20:57
  • @Timo its been a while since I made this comment. I think slice(-1) is preferable if you want to return the result as an array result (['action']). If you want the result to be a string (action), then use pop().
    – kimbaudi
    Mar 20 at 0:39
9

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

1

Or the regex way:

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

OR

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

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

1
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.