Reputation: 21308
What is the best way to get the Last segment of the URL (omitting any parameters). Also url may or may not include the last '/' character
for example
http://Home/Billing/Index.html?param1=2&another=2
should result in: Index.html
http://Home/Billing/Index.html/
should result in: Index.html
I've tried this but i can't get how to check for the last /
ar href = window.location.pathname;
var value = href.lastIndexOf('/') + 1);
Upvotes: 1
Views: 1594
Reputation: 7795
@psantiago answer works great. If you want to do the same but using RegEx you can implement as follows:
var r = /(\/([A-Za-z0-9\.]+)(\??|\/?|$))+/;
r.exec("http://Home/Billing/Index.html?param1=2&another=2")[2]; //outputs: Index.html
r.exec("http://Home/Billing/Index.html/"); //outputs: Index.html
In my opinion, the above code is more efficient and cleaner than using split operations.
Upvotes: 1
Reputation: 714
Maybe something like?
window.location.pathname.split('?')[0].split('/').filter(function (i) { return i !== ""}).slice(-1)[0]
Upvotes: 1