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];
source share