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
//mywebsite/folder/file
how do I only get it to display the "file" part of the url in the alert box?
isherwood
54k15 gold badges105 silver badges147 bronze badges
asked Jan 21, 2011 at 11:11
oshirowanenoshirowanen
15.8k80 gold badges192 silver badges344 bronze badges
1
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.
3065068
554 silver badges10 bronze badges
answered Jan 21, 2011 at 11:18
Frédéric HamidiFrédéric Hamidi
252k41 gold badges471 silver badges469 bronze badges
18
var parts = '//mywebsite/folder/file'.split['/'];
var lastSegment = parts.pop[] || parts.pop[]; // handle potential trailing slash
console.log[lastSegment];
Chris Happy
6,7331 gold badge20 silver badges43 bronze badges
answered Oct 28, 2012 at 11:35
Tim van OostromTim van Oostrom
1,8911 gold badge12 silver badges7 bronze badges
3
window.location.pathname.split["/"].pop[]
answered Nov 21, 2016 at 16:56
1
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 = '//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].
answered Aug 10, 2018 at 23:27
Sebastian BarthSebastian Barth
3,7656 gold badges37 silver badges54 bronze badges
1
Just another solution with regex.
var href = location.href;
console.log[href.match[/[[^\/]*]\/*$/][1]];
answered Apr 20, 2016 at 10:56
AvirtumAvirtum
4286 silver badges14 bronze badges
0
Javascript has the function split associated to string object that can help you:
var url = "//mywebsite/folder/file";
var array = url.split['/'];
var lastsegment = array[array.length-1];
answered Jan 21, 2011 at 11:14
Fran VeronaFran Verona
5,3705 gold badges45 silver badges84 bronze badges
0
Or you could use a regular expression:
alert[href.replace[/.*\//, '']];
answered Jan 21, 2011 at 11:21
jasssonpetjasssonpet
2,05916 silver badges18 bronze badges
1
var urlChunks = 'mywebsite/folder/file'.split['/'];
alert[urlChunks[urlChunks.length - 1]];
answered Jan 21, 2011 at 11:14
acmeacme
14.3k7 gold badges73 silver badges106 bronze badges
// //x.com/boo/?q=foo&s=bar = boo
// //x.com/boo?q=foo&s=bar = boo
// //x.com/boo/ = boo
// //x.com/boo = boo
const segment = new
URL[window.location.href].pathname.split['/'].filter[Boolean].pop[];
console.log[segment];
Works for me.
answered Apr 30, 2019 at 19:26
Returns the last segment, regardless of trailing slashes:
var val = '//mywebsite/folder/file//'.split['/'].filter[Boolean].pop[];
console.log[val];
answered Aug 21, 2018 at 12:46
John DohertyJohn Doherty
3,27132 silver badges36 bronze badges
3
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
//test.com/#/about/us/
or
//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['//test.com/dir/index.html?key=value'];
var lastSegment = url.segment[].pop[]; // index.html
answered Jun 20, 2013 at 13:10
IL55IL55
8801 gold badge8 silver badges15 bronze badges
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 = '//mywebsite/folder/file';
let lastSegment = str.replace[/.*\/[\w+]\/?$/, '$1'];
console.log[lastSegment];
answered Dec 9, 2020 at 5:40
Also,
var url = $[this].attr["href"];
var part = url.substring[url.lastIndexOf['/'] + 1];
answered Jan 21, 2011 at 11:18
naveennaveen
51.8k46 gold badges158 silver badges243 bronze badges
Building on Frédéric's answer using only javascript:
var url = document.URL
window.alert[url.substr[url.lastIndexOf['/'] + 1]];
answered Jan 13, 2015 at 18:02
PinchPinch
3,8218 gold badges37 silver badges59 bronze badges
1
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[]
answered May 11, 2015 at 16:24
Jaboc83Jaboc83
3021 gold badge2 silver badges8 bronze badges
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 //quux.com/path/to/foo?bar#baz
] use this:
window.alert[this.pathname.substr[this.pathname.lastIndexOf['/'] + 1] + this.search + this.hash];
answered Jan 21, 2011 at 11:43
WalfWalf
7,8312 gold badges40 silver badges57 bronze badges
0
To get the last segment of your current window:
window.location.href.substr[window.location.href.lastIndexOf['/'] +1]
answered May 23, 2017 at 10:31
RegarBoyRegarBoy
2,9081 gold badge19 silver badges44 bronze badges
1
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];
answered Aug 1, 2018 at 14:49
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
Copied from this answer
answered Jan 14, 2016 at 16:02
// Store original location in loc like: //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:
//test.com/one/
or
//test.com/one
or
//test.com/one/index.htm
Then loc ends up looking like: //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: //test.com/one/ [ending slash]
let loc = "//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];
answered Jun 17, 2015 at 19:19
raddevusraddevus
7,4675 gold badges61 silver badges74 bronze badges
4
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,2733 gold badges14 silver badges19 bronze badges
answered Feb 21, 2018 at 13:01
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:
[^\/]+[\/]?$
answered Aug 27, 2018 at 12:40
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.
answered Jul 8, 2019 at 3:47
Ruan CarlosRuan Carlos
4755 silver badges9 bronze badges
if the url is //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
answered Dec 30, 2019 at 22:06
DijiflexDijiflex
3935 silver badges17 bronze badges
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;
}, ""];
- Split the string on path separators.
- Filter out empty string path parts [this could happen with trailing slash in path].
- Reduce the array of path parts to the last one.
answered Jun 17, 2020 at 17:36
AaronAaron
3,1243 gold badges32 silver badges48 bronze badges
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];
}
answered Aug 1 at 0:11
mrbarlettamrbarletta
86211 silver badges16 bronze badges
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]];
answered May 22, 2018 at 12:34
Jaison JamesJaison James
4,1604 gold badges36 silver badges51 bronze badges
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['Best '+lastSegment+' Deals
'];
}];
answered Aug 26, 2021 at 9:43
Ashar ZafarAshar Zafar
3782 silver badges11 bronze badges
A way to avoid query params
const urlString = "//stackoverflow.com/last-segment?param=123"
const url = new URL[urlString];
url.search = '';
const lastSegment = url.pathname.split['/'].pop[];
console.log[lastSegment]
answered Jun 9 at 15:33
TakyoTakyo
1091 silver badge3 bronze badges