ShaneKm
ShaneKm

Reputation: 21308

JavaScript get last URL segment

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

Answers (2)

Alan Souza
Alan Souza

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

psantiago
psantiago

Reputation: 714

Maybe something like?

window.location.pathname.split('?')[0].split('/').filter(function (i) { return i !== ""}).slice(-1)[0]
  1. Split on '?' to throw out any query string parameters
  2. Get the first of those splits
  3. Split on '/'.
  4. For all those splits, filter away all the empty strings
  5. Get the last one remaining

Upvotes: 1

Related Questions