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(\
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);
To get the last segment of your current window:
window.location.href.substr(window.location.href.lastIndexOf('/') +1)
// https://x.com/boo/?q=foo&s=bar = boo
// https://x.com/boo?q=foo&s=bar = boo
// https://x.com/boo/ = boo
// https://x.com/boo = boo
const segment = new
URL(window.location.href).pathname.split('/').filter(Boolean).pop();
console.log(segment);
Works for me.
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
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
Copied from this answer
var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
console.log(lastSegment);