1

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);
ShaneKm
  • 20,823
  • 43
  • 167
  • 296
  • something like this http://stackoverflow.com/questions/1302306/how-to-pull-the-file-name-from-a-url-using-javascript-jquery ? – Dhiraj May 29 '15 at 15:43
  • possible duplicate of [FileName from url excluding querystring](http://stackoverflow.com/questions/6035352/filename-from-url-excluding-querystring) – Qantas 94 Heavy May 29 '15 at 15:45
  • 2
    both of these don't take under account the last '/' character. Pls take a look at example 2 I posted – ShaneKm May 29 '15 at 15:47

2 Answers2

1

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
psantiago
  • 695
  • 6
  • 16
1

@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.

Alan Souza
  • 7,475
  • 10
  • 46
  • 68