322

How do I get the last segment of a url? I have the following script which displays the full url of the anchor tag clicked:

$(".tag_name_goes_here").live('click', function(event)
{
    event.preventDefault();  
    alert($(this).attr("href"));
});

If the url is

http://mywebsite/folder/file

how do I only get it to display the "file" part of the url in the alert box?

1
  • 2
    Please, do not use a naive solution that splits the href by /. A URL has parts after the path: the search parameters (after ?), and the fragment (after #). If you have a URL as a string, use new URL( the string ).pathname first. If you’re looking for the URL of the current page, use location.pathname. Then use .split("/") on the result. .filter(Boolean) removes empty parts (e.g. after trailing slashes). .at(-1) (or .pop() or .slice(-1)[0]) gets the last part of the path. Mar 15, 2022 at 22:08

30 Answers 30

475

You can also use the lastIndexOf() function to locate the last occurrence of the / character in your URL, then the substring() function to return the substring starting from that location:

console.log(this.href.substring(this.href.lastIndexOf('/') + 1));

That way, you'll avoid creating an array containing all your URL segments, as split() does.

18
  • 4
    @oshirowanen, no, but it will create an array element from each URL segment. Since you're only interested in the last segment, it might be wasteful to allocate many array elements that you'll never use. Jan 21, 2011 at 11:23
  • 27
    But if the url was become like admin/store/tour/-1/ so it's will be '' string? Aug 20, 2014 at 8:39
  • 1
    @Set, nicer maybe, slower surely. Aug 20, 2014 at 8:58
  • 3
    what if the url contains a / at the end? Jul 25, 2016 at 14:07
  • 10
    Attn: @Set Kyar Wa Lar Aug and @Sнаđошƒаӽ Solution for url that contains a / at the end: var url = window.location.href.replace(/\/$/, ''); /* remove optional end / */ var lastSeg = url.substr(url.lastIndexOf('/') + 1);
    – Ross
    Nov 2, 2016 at 3:18
177

var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop();  // handle potential trailing slash

console.log(lastSegment);

4
  • Can you explain me how it work's? as per my knowledge .pop() used for remove last element of a array. but is here it showed last element of my url!! Dec 15, 2015 at 7:33
  • 1
    Split will convert your url into an array taking each section of the url delimited by '/'. Hence the last segment is the last element of both the url and the subsequently created array.
    – stephen
    Feb 22, 2016 at 23:46
  • 4
    Sidenote: This does not work if the URL does have query params set on it (e.g. .../file?var=value&foo=bar). This solution solves this problem on a more robust and modern way: stackoverflow.com/a/51795122/1123743 May 18, 2020 at 14:01
  • @SebastianBarth: var lastSegment = parts.pop().split('?')[0] || parts.pop();
    – Mori
    Mar 31, 2023 at 14:05
164
window.location.pathname.split("/").pop()
1
  • 1
    This is exactly what I was looking for. Using react-router-dom this was the cleanest solution I have found to find the last part of the URL trailing the last forward slash /. console.log(history.location.pathname.split("/").pop()) If there is a better way I would like to know! Hopefully this comment can lead more people to your answer. Thanks @Dblock247
    – tralawar
    Dec 26, 2019 at 21:48
56

The other answers may work if the path is simple, consisting only of simple path elements. But when it contains query params as well, they break.

Better use URL object for this instead to get a more robust solution. It is a parsed interpretation of the present URL:

Input: const href = 'https://stackoverflow.com/boo?q=foo&s=bar'

const segments = new URL(href).pathname.split('/');
const last = segments.pop() || segments.pop(); // Handle potential trailing slash
console.log(last);

Output: 'boo'

This works for all common browsers. Only our dying IE doesn't support that (and won't). For IE there is a polyfills available, though (if you care at all).

3
  • 1
    In case someone doesn't grok what's going on here: segments will be an array of all the paths, so if you have a URL like: https://a.com/b/c/d/?letters=true then segments in this example is equal to ['b', 'c', 'd', ''] because the trailing slash after d results in an empty string ''. Then the last variable is saying "grab the last item from the segments array and remove it. If this item is falsy then do the same thing again" (logical OR) which results in returning d from my example here.
    – maxshuty
    Feb 24, 2022 at 12:11
  • @Sebastian Barth, How to get the last part after equal. I mean bar.
    – Kaizur
    Oct 9, 2022 at 11:31
  • @Kaizur Those are query parameters. See How can I get query string values in JavaScript?. Oct 9, 2022 at 19:37
40

Just another solution with regex.

var href = location.href;
console.log(href.match(/([^\/]*)\/*$/)[1]);
0
34

Javascript has the function split associated to string object that can help you:

const url = "http://mywebsite/folder/file";
const array = url.split('/');

const lastsegment = array[array.length-1];
0
17

Shortest way how to get URL Last Segment with split(), filter() and pop()

function getLastUrlSegment(url) {
  return new URL(url).pathname.split('/').filter(Boolean).pop();
}

console.log(getLastUrlSegment(window.location.href));
console.log(getLastUrlSegment('https://x.com/boo'));
console.log(getLastUrlSegment('https://x.com/boo/'));
console.log(getLastUrlSegment('https://x.com/boo?q=foo&s=bar=aaa'));
console.log(getLastUrlSegment('https://x.com/boo?q=foo#this'));
console.log(getLastUrlSegment('https://x.com/last segment with spaces'));

Works for me.

1
  • this seems like best solution works with
    – OzzyCzech
    Sep 27, 2022 at 8:32
11

Or you could use a regular expression:

alert(href.replace(/.*\//, ''));
1
9
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);
7

Returns the last segment, regardless of trailing slashes:

var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();

console.log(val);

4
  • You probably want to use path.sep not a literal slash. See nodejs.org/api/path.html#path_path_sep. This will keep your code portable across OSs.
    – Aaron
    Jun 17, 2020 at 17:10
  • 2
    Nice idea, but it would no longer work in the browser Jun 17, 2020 at 23:09
  • good point. I should say that this is preferred in command line scripts/server-side nodejs.
    – Aaron
    Jun 20, 2020 at 17:58
  • 1
    Well, I recommend this solution. I used in my React project Nov 24, 2022 at 19:29
5

I know, it is too late, but for others: I highly recommended use PURL jquery plugin. Motivation for PURL is that url can be segmented by '#' too (example: angular.js links), i.e. url could looks like

    http://test.com/#/about/us/

or

    http://test.com/#sky=blue&grass=green

And with PURL you can easy decide (segment/fsegment) which segment you want to get.

For "classic" last segment you could write:

    var url = $.url('http://test.com/dir/index.html?key=value');
    var lastSegment = url.segment().pop(); // index.html
4

Get the Last Segment using RegEx

str.replace(/.*\/(\w+)\/?$/, '$1');

$1 means using the capturing group. using in RegEx (\w+) create the first group then the whole string replace with the capture group.

let str = 'http://mywebsite/folder/file';
let lastSegment = str.replace(/.*\/(\w+)\/?$/, '$1');
console.log(lastSegment);

3

Also,

var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
3

Building on Frédéric's answer using only javascript:

var url = document.URL

window.alert(url.substr(url.lastIndexOf('/') + 1));
1
  • substr is deprecated; this doesn’t handle parts of the URL which come after the path. Mar 15, 2022 at 21:54
3

If you aren't worried about generating the extra elements using the split then filter could handle the issue you mention of the trailing slash (Assuming you have browser support for filter).

url.split('/').filter(function (s) { return !!s }).pop()
3
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));

Use the native pathname property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href") can return values like ../.. which would not give you the correct result.

If you need to keep the search and hash (e.g. foo?bar#baz from http://quux.com/path/to/foo?bar#baz) use this:

window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);
0
3

To get the last segment of your current window:

window.location.href.substr(window.location.href.lastIndexOf('/') +1)

1
  • 1
    substr is deprecated; this doesn’t handle parts of the URL which come after the path. Mar 15, 2022 at 21:49
3

you can first remove if there is / at the end and then get last part of url

let locationLastPart = window.location.pathname
if (locationLastPart.substring(locationLastPart.length-1) == "/") {
  locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
}
locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);
2
var pathname = window.location.pathname; // Returns path only
var url      = window.location.href;     // Returns full URL

Copied from this answer

2
// Store original location in loc like: http://test.com/one/ (ending slash)
var loc = location.href; 
// If the last char is a slash trim it, otherwise return the original loc
loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substring(0,loc.length-1) : loc.substring(0,loc.lastIndexOf('/'));
var targetValue = loc.substring(loc.lastIndexOf('/') + 1);

targetValue = one

If your url looks like:

http://test.com/one/

or

http://test.com/one

or

http://test.com/one/index.htm

Then loc ends up looking like: http://test.com/one

Now, since you want the last item, run the next step to load the value (targetValue) you originally wanted.

var targetValue = loc.substr(loc.lastIndexOf('/') + 1);

// Store original location in loc like: http://test.com/one/ (ending slash)
    let loc = "http://test.com/one/index.htm"; 
   console.log("starting loc value = " + loc);
    // If the last char is a slash trim it, otherwise return the original loc
    loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substring(0,loc.length-1) : loc.substring(0,loc.lastIndexOf('/'));
    let targetValue = loc.substring(loc.lastIndexOf('/') + 1);
console.log("targetValue = " + targetValue);
console.log("loc = " + loc);

4
  • I probably miss something, but with "test.com/one" loc ends up looking like : "test.com". I think it should be like : if( loc.lastIndexOf('/') == (loc.length -1) ){ loc = loc.substr(0,loc.length-1) }else{ var isFile = loc.substr(loc.lastIndexOf('/'),loc.length).indexOf('.') != -1; if(isFile) loc = loc.substr(0,loc.lastIndexOf('/')); } Aug 3, 2016 at 13:53
  • Fails if slash in search or hash.
    – Walf
    Aug 4, 2016 at 0:42
  • substr is deprecated; this doesn’t handle parts of the URL which come after the path. Mar 15, 2022 at 21:51
  • Yeah, a lot has changed since I originally created this old answer. I updated the code so it works properly with String.substring() & added a running code example.
    – raddevus
    Mar 16, 2022 at 13:49
1

Updated raddevus answer :

var loc = window.location.href;
loc = loc.lastIndexOf('/') == loc.length - 1 ? loc.substr(0, loc.length - 1) : loc.substr(0, loc.length + 1);
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);

Prints last path of url as string :

test.com/path-name = path-name

test.com/path-name/ = path-name
0

I am using regex and split:

var last_path = location.href.match(/./(.[\w])/)[1].split("#")[0].split("?")[0]

In the end it will ignore # ? & / ending urls, which happens a lot. Example:

https://cardsrealm.com/profile/cardsRealm -> Returns cardsRealm

https://cardsrealm.com/profile/cardsRealm#hello -> Returns cardsRealm

https://cardsrealm.com/profile/cardsRealm?hello -> Returns cardsRealm

https://cardsrealm.com/profile/cardsRealm/ -> Returns cardsRealm

0

I don't really know if regex is the right way to solve this issue as it can really affect efficiency of your code, but the below regex will help you fetch the last segment and it will still give you the last segment even if the URL is followed by an empty /. The regex that I came up with is:

[^\/]+[\/]?$
0

I know it is old but if you want to get this from an URL you could simply use:

document.location.pathname.substring(document.location.pathname.lastIndexOf('/.') + 1);

document.location.pathname gets the pathname from the current URL. lastIndexOf get the index of the last occurrence of the following Regex, in our case is /.. The dot means any character, thus, it will not count if the / is the last character on the URL. substring will cut the string between two indexes.

0

if the url is http://localhost/madukaonline/shop.php?shop=79

console.log(location.search); will bring ?shop=79

so the simplest way is to use location.search

you can lookup for more info here and here

0

You can do this with simple paths (w/0) querystrings etc.

Granted probably overly complex and probably not performant, but I wanted to use reduce for the fun of it.

  "/foo/bar/"
    .split(path.sep)
    .filter(x => x !== "")
    .reduce((_, part, i, arr) => {
      if (i == arr.length - 1) return part;
    }, "");
  1. Split the string on path separators.
  2. Filter out empty string path parts (this could happen with trailing slash in path).
  3. Reduce the array of path parts to the last one.
0

Adding up to the great Sebastian Barth answer.

if href is a variable that you are parsing, new URL will throw a TypeError so to be in the safe side you should try - catch

try{    
    const segments = new URL(href).pathname.split('/');
    const last = segments.pop() || segments.pop(); // Handle potential trailing slash
    console.log(last);
}catch (error){
    //Uups, href wasn't a valid URL (empty string or malformed URL)
    console.log('TypeError ->',error);
}
-1

I believe it's safer to remove the tail slash('/') before doing substring. Because I got an empty string in my scenario.

window.alert((window.location.pathname).replace(/\/$/, "").substr((window.location.pathname.replace(/\/$/, "")).lastIndexOf('/') + 1));
1
-1

Bestway to get URL Last Segment Remove (-) and (/) also

 jQuery(document).ready(function(){
        var path = window.location.pathname;
        var parts = path.split('/');
        var lastSegment = parts.pop() || parts.pop();  // handle potential trailing slash
        lastSegment = lastSegment.replace('-',' ').replace('-',' ');
        jQuery('.archive .filters').before('<div class="product_heading"><h3>Best '+lastSegment+' Deals </h3></div>');
    
    }); 
-1

A way to avoid query params

const urlString = "https://stackoverflow.com/last-segment?param=123"
const url = new URL(urlString);
url.search = '';
const lastSegment = url.pathname.split('/').pop();

console.log(lastSegment)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.