314

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?

isherwood
  • 58,414
  • 16
  • 114
  • 157
oshirowanen
  • 15,297
  • 82
  • 198
  • 350
  • 2
    Please, **do not use a naive solution** that splits the `href` by `/`. A [URL](//en.wikipedia.org/wiki/URL#Syntax) has parts _after_ the path: the search parameters (after `?`), and the fragment (after `#`). If you have a URL as a string, use `new `[`URL`](//developer.mozilla.org/docs/Web/API/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. – Sebastian Simon Mar 15 '22 at 22:08

30 Answers30

468

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.

Jan
  • 55
  • 2
  • 11
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • Will the split version cause an issue if the number of '/' change in the URL? – oshirowanen Jan 21 '11 at 11:21
  • 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. – Frédéric Hamidi Jan 21 '11 at 11:23
  • I had trouble with the initial statement in Chrome, the follow worked for me for line 1: $(window.location).attr('href') – Levi May 13 '14 at 14:23
  • 26
    But if the url was become like `admin/store/tour/-1/` so it's will be `''` string? – Set Kyar Wa Lar Aug 20 '14 at 08:39
  • @Set, yes, this solution (as well as the "`split()` then `pop()`" alternative) will return an empty string if the URL ends with a slash character (mostly because this question was not about such URLs in the first place). – Frédéric Hamidi Aug 20 '14 at 08:42
  • I think using split is more nicer. Something like `var url_split = window.location.pathname.split( '/' ); var id = url_split[4];` @FrédéricHamidi – Set Kyar Wa Lar Aug 20 '14 at 08:57
  • 1
    @Set, nicer maybe, slower surely. – Frédéric Hamidi Aug 20 '14 at 08:58
  • 3
    what if the url contains a `/` at the end? – Sнаđошƒаӽ Jul 25 '16 at 14:07
  • 1
    For future readers, **do not rely on the `href` *attribute***, it is unresolved and can contain things like `../` meaning up one directory. **Use the native *property*** instead, like `this.href`. – Walf Aug 04 '16 at 00:53
  • @Walf, my bad, I should have migrated this older answer to `prop()` already. Thanks for the heads-up :) – Frédéric Hamidi Sep 26 '16 at 21:21
  • You don't need to wrap it in a jQuery object just to access its native property. – Walf Sep 27 '16 at 00:37
  • 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 02 '16 at 03:18
  • 1
    You also can use following syntax.. `document.location.href.substr(document.location.href.lastIndexOf('/') + 1)` – vipmaa Jan 26 '17 at 09:12
  • 1
    https://stackoverflow.com/a/51795122/3492994 has a better, more foolproof solution. – Stefnotch Jan 05 '19 at 20:47
  • **note**: `'foo'.substr('foo'.lastIndexOf('/') + 1)` returns `oo` – luukvhoudt Oct 24 '19 at 22:39
  • @Fleuv, you should try that again. Since `lastIndexOf()` returns `-1` when no match is found, what you say is not possible. And indeed, a quick copy-paste of your sample does return `foo`, both in Node and in my browser's console. – Frédéric Hamidi Oct 25 '19 at 06:43
  • 1
    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: https://stackoverflow.com/a/51795122/1123743 – Sebastian Barth May 18 '20 at 14:04
  • had to get the last element in url, with vue(nuxt), could do it with this line: var lastEl = this.$route.path; console.log(lastEl.substring(lastEl.lastIndexOf('/') + 1)) –  Jul 31 '20 at 09:39
172

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

console.log(lastSegment);
Chris Happy
  • 7,088
  • 2
  • 22
  • 49
Tim van Oostrom
  • 1,961
  • 1
  • 12
  • 8
  • 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!! – Inspire Shahin Dec 15 '15 at 07: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 '16 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: https://stackoverflow.com/a/51795122/1123743 – Sebastian Barth May 18 '20 at 14:01
  • @SebastianBarth: `var lastSegment = parts.pop().split('?')[0] || parts.pop();` – Mori Mar 31 '23 at 14:05
155
window.location.pathname.split("/").pop()
Dblock247
  • 6,167
  • 10
  • 44
  • 66
  • 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 '19 at 21:48
55

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

Sebastian Barth
  • 4,079
  • 7
  • 40
  • 59
  • 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 '22 at 12:11
  • @Sebastian Barth, How to get the last part after equal. I mean bar. – Kaizur Oct 09 '22 at 11:31
  • @Kaizur Those are query parameters. See [How can I get query string values in JavaScript?](/a/901144/4642212). – Sebastian Simon Oct 09 '22 at 19:37
40

Just another solution with regex.

var href = location.href;
console.log(href.match(/([^\/]*)\/*$/)[1]);
Avirtum
  • 438
  • 6
  • 14
33

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];
Fran Verona
  • 5,438
  • 6
  • 46
  • 85
16

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.

OzzyCzech
  • 9,713
  • 3
  • 50
  • 34
sanyaissues
  • 161
  • 2
  • 5
11

Or you could use a regular expression:

alert(href.replace(/.*\//, ''));
jasssonpet
  • 2,079
  • 15
  • 18
  • 1
    better yet, combine this with https://stackoverflow.com/questions/4758103/last-segment-of-url#comment67997244_4758173 : `alert(window.location.href.replace(/\/$/, '').replace(/.*//, ''))` – samson Mar 21 '20 at 04:36
9
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);
acme
  • 14,654
  • 7
  • 75
  • 109
7

Returns the last segment, regardless of trailing slashes:

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

console.log(val);
John Doherty
  • 3,669
  • 36
  • 38
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
IL55
  • 910
  • 1
  • 9
  • 15
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);
Aman Silawat
  • 501
  • 4
  • 8
3

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

var url = document.URL

window.alert(url.substr(url.lastIndexOf('/') + 1));
Pinch
  • 4,009
  • 8
  • 40
  • 60
  • [`substr`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substr) is deprecated; this doesn’t handle parts of the URL which come after the path. – Sebastian Simon Mar 15 '22 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()
Jaboc83
  • 302
  • 1
  • 2
  • 8
3

To get the last segment of your current window:

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

RegarBoy
  • 3,228
  • 1
  • 23
  • 44
  • 1
    [`substr`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substr) is deprecated; this doesn’t handle parts of the URL which come after the path. – Sebastian Simon Mar 15 '22 at 21:49
3

Also,

var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
naveen
  • 53,448
  • 46
  • 161
  • 251
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);
Walf
  • 8,535
  • 2
  • 44
  • 59
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);
Veysi YILDIZ
  • 99
  • 1
  • 2
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);
raddevus
  • 8,142
  • 7
  • 66
  • 87
  • I probably miss something, but with "http://test.com/one" loc ends up looking like : "http://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('/')); } – Allan Raquin Aug 03 '16 at 13:53
  • Fails if slash in `search` or `hash`. – Walf Aug 04 '16 at 00:42
  • [`substr`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substr) is deprecated; this doesn’t handle parts of the URL which come after the path. – Sebastian Simon Mar 15 '22 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 '22 at 13:49
2
var pathname = window.location.pathname; // Returns path only
var url      = window.location.href;     // Returns full URL

Copied from this answer

Community
  • 1
  • 1
Roberto Alonso
  • 1,181
  • 1
  • 7
  • 9
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
F0XS
  • 1,271
  • 3
  • 15
  • 19
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

Dinidiniz
  • 771
  • 9
  • 15
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.

Ruan Carlos
  • 485
  • 5
  • 9
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

Dijiflex
  • 523
  • 1
  • 8
  • 26
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.
Aaron
  • 3,249
  • 4
  • 35
  • 51
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);
}
mrbarletta
  • 902
  • 11
  • 17
-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));
Jaison James
  • 4,414
  • 4
  • 42
  • 54
-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>');
    
    }); 
Ashar Zafar
  • 382
  • 2
  • 11
-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)
Takyo
  • 111
  • 1
  • 3