oshirowanen
oshirowanen

Reputation: 15925

Last segment of URL with JavaScript

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?

Upvotes: 328

Views: 448192

Answers (28)

Dinidiniz
Dinidiniz

Reputation: 811

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

Upvotes: 0

Fran Verona
Fran Verona

Reputation: 5476

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];

Upvotes: 35

sanyaissues
sanyaissues

Reputation: 171

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.

Upvotes: 17

mrbarletta
mrbarletta

Reputation: 922

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);
}

Upvotes: 0

raddevus
raddevus

Reputation: 9077

// 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);

Upvotes: 2

Ashar Zafar
Ashar Zafar

Reputation: 402

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>');
    
    }); 

Upvotes: -1

Aman Silawat
Aman Silawat

Reputation: 571

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

Upvotes: 4

Sebastian Barth
Sebastian Barth

Reputation: 4521

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

Upvotes: 59

Aaron
Aaron

Reputation: 3399

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.

Upvotes: 0

Ruan Carlos
Ruan Carlos

Reputation: 505

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.

Upvotes: 0

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262919

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.

Upvotes: 481

John Doherty
John Doherty

Reputation: 4085

Returns the last segment, regardless of trailing slashes:

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

console.log(val);

Upvotes: 7

user9628338
user9628338

Reputation:

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:

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

Upvotes: 0

Veysi YILDIZ
Veysi YILDIZ

Reputation: 109

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

Upvotes: 3

Jaison James
Jaison James

Reputation: 4552

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

Upvotes: -1

Nemanja Smiljanic
Nemanja Smiljanic

Reputation: 11

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

Upvotes: 1

Tim van Oostrom
Tim van Oostrom

Reputation: 2061

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

console.log(lastSegment);

Upvotes: 182

RegarBoy
RegarBoy

Reputation: 3521

To get the last segment of your current window:

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

Upvotes: 3

Dblock247
Dblock247

Reputation: 6725

window.location.pathname.split("/").pop()

Upvotes: 170

Walf
Walf

Reputation: 9278

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

Upvotes: 3

Max Lawrence
Max Lawrence

Reputation: 438

Just another solution with regex.

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

Upvotes: 40

Roberto Alonso
Roberto Alonso

Reputation: 1201

var pathname = window.location.pathname; // Returns path only
var url      = window.location.href;     // Returns full URL

Copied from this answer

Upvotes: 2

Jaboc83
Jaboc83

Reputation: 302

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

Upvotes: 3

Pinch
Pinch

Reputation: 4207

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

var url = document.URL

window.alert(url.substr(url.lastIndexOf('/') + 1));

Upvotes: 3

IL55
IL55

Reputation: 920

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

Upvotes: 5

jasssonpet
jasssonpet

Reputation: 2119

Or you could use a regular expression:

alert(href.replace(/.*\//, ''));

Upvotes: 11

codeandcloud
codeandcloud

Reputation: 55200

Also,

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

Upvotes: 3

acme
acme

Reputation: 14856

var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);

Upvotes: 9

Related Questions