0

Ho do I get the last part of a URL segment excluding any URL parameters.

So if I'm on this page:

http://example.com/myfolder/mypage.aspx?x=1

I want to get:

mypage.aspx
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
adam78
  • 9,668
  • 24
  • 96
  • 207

2 Answers2

1

You can do something this way:

// The first thing is to strip off the things after query string:
var url = "http://example.com/myfolder/mypage.aspx?x=1";
url = url.split("?")
url = url[0];
// Get the last path:
url = url.split("/");
page = url[url.length-1];
alert(page);

The above path will work even if there's no ? in it.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
-2

Or you can just do it oneliner:

const lastPart = url.split('?')[0].split('/').at(-1);
Ron Jonk
  • 706
  • 6
  • 16