Get the last part of the URI

I need to get the last part of the current URI using Javascript, e.g. for

www.example.com/apple/beer/cucumber

he must return

cucumber

or

www.example.com/apple/beer/

he must return

beer

I came up with the following code:

var url = window.location.pathname; var urlsplit = url.split("/"); var action = urlsplit[urlsplit.length-1]; 

Can this be improved? If not, perhaps this post will help others who are trying to find a solution to the same problem.

Decision

Thanks to everyone, this seems like the shortest (hopefully the best) solution:

 var action = window.location.pathname.split("/").slice(-1)[0]; 
+6
source share
4 answers

This is a little shorter, but your decision is certainly the right one.

 var url = window.location.pathname; var urlsplit = url.split("/").slice(-1)[0]; 

Or, as PSR says, you can use substr:

 var url = window.location.pathname; url.substr(url.lastIndexOf('/') + 1); 
+8
source

Unfortunately, none of the answers so far works with URLs with trailing / as your example www.example.com/apple/beer/ .
Here is a solution that also works in this case:

 window.location.pathname.split('/').filter(function(el){ return !!el; }).pop(); 

jsFiddle Testcase: http://jsfiddle.net/EMK6t/

+9
source

you can use

 url.substr(url.lastIndexOf('/') + 1) 
+1
source

location.pathname.match(/([^\/]+)$/)[1]

This essentially means that all characters that are not a slash at the end of the path return this sequence.

-1
source

Source: https://habr.com/ru/post/943712/


All Articles