Last segment of URL
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?
javascript jquery
add a comment |
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?
javascript jquery
Below is my working java script solution.Hope it helps. stackoverflow.com/a/38370175/610951
– Ravi
Jul 14 '16 at 9:19
add a comment |
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?
javascript jquery
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?
javascript jquery
javascript jquery
edited Jan 21 '11 at 11:25


Felix Kling
546k126849909
546k126849909
asked Jan 21 '11 at 11:11
oshirowanenoshirowanen
3,07071162305
3,07071162305
Below is my working java script solution.Hope it helps. stackoverflow.com/a/38370175/610951
– Ravi
Jul 14 '16 at 9:19
add a comment |
Below is my working java script solution.Hope it helps. stackoverflow.com/a/38370175/610951
– Ravi
Jul 14 '16 at 9:19
Below is my working java script solution.Hope it helps. stackoverflow.com/a/38370175/610951
– Ravi
Jul 14 '16 at 9:19
Below is my working java script solution.Hope it helps. stackoverflow.com/a/38370175/610951
– Ravi
Jul 14 '16 at 9:19
add a comment |
22 Answers
22
active
oldest
votes
You can also use the lastIndexOf() function to locate the last occurrence of the /
character in your URL, then the substr() function to return the substring starting from that location:
window.alert(this.href.substr(this.href.lastIndexOf('/') + 1));
That way, you'll avoid creating an array containing all your URL segments, as split()
does.
2
@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
7
But if the url was become likeadmin/store/tour/-1/
so it's will be''
string?
– Set Kyar Wa Lar
Aug 20 '14 at 8:39
1
@Set, nicer maybe, slower surely.
– Frédéric Hamidi
Aug 20 '14 at 8:58
1
For future readers, do not rely on thehref
attribute, it is unresolved and can contain things like../
meaning up one directory. Use the native property instead, likethis.href
.
– Walf
Aug 4 '16 at 0:53
3
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 '16 at 3:18
|
show 10 more comments
var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
console.log(lastSegment);
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 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 '16 at 23:46
9
This won't work if the url ends with a "/" i.e.http://mywebsite/folder/file/
– Peter Ludlow
Feb 25 '16 at 4:40
add a comment |
window.location.pathname.split("/").pop()
simple and easy. Thanks.
– krezaeim
Sep 24 '18 at 18:01
Perfect and tidy, great
– Babak Habibi
Oct 11 '18 at 12:29
add a comment |
Just another solution with regex.
var href = location.href;
console.log(href.match(/([^/]*)/*$/)[1]);
2
this works great if URL ends with /
– Shoaib Iqbal
Nov 14 '16 at 6:00
add a comment |
Javascript has the function split associated to string object that can help you:
var url = "http://mywebsite/folder/file";
var array = url.split('/');
var lastsegment = array[array.length-1];
add a comment |
Or you could use a regular expression:
alert(href.replace(/.*//, ''));
add a comment |
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);
add a comment |
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
add a comment |
Building on Frédéric's answer using only javascript:
var url = document.URL
window.alert(url.substr(url.lastIndexOf('/') + 1));
add a comment |
Also,
var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
add a comment |
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()
add a comment |
// 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.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
var targetValue = loc.substr(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);
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('/')); }
– Allan Raquin
Aug 3 '16 at 13:53
Fails if slash insearch
orhash
.
– Walf
Aug 4 '16 at 0:42
add a comment |
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);
Also want to add thatpathname
strips query parameters, buthref
does not.
– Max Heiber
Aug 3 '16 at 15:33
add a comment |
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 last = new URL(href).pathname.split('/').pop();
console.log(last);
Output: 'boo'
add a comment |
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
Copied from this answer
add a comment |
To get the last segment of your current window:
window.location.href.substr(window.location.href.lastIndexOf('/') +1)
add a comment |
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
add a comment |
Returns the last segment, regardless of trailing slashes:
var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();
console.log(val);
add a comment |
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));
add a comment |
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
add a comment |
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);
add a comment |
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:
[^/]+[/]?$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4758103%2flast-segment-of-url%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
22 Answers
22
active
oldest
votes
22 Answers
22
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can also use the lastIndexOf() function to locate the last occurrence of the /
character in your URL, then the substr() function to return the substring starting from that location:
window.alert(this.href.substr(this.href.lastIndexOf('/') + 1));
That way, you'll avoid creating an array containing all your URL segments, as split()
does.
2
@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
7
But if the url was become likeadmin/store/tour/-1/
so it's will be''
string?
– Set Kyar Wa Lar
Aug 20 '14 at 8:39
1
@Set, nicer maybe, slower surely.
– Frédéric Hamidi
Aug 20 '14 at 8:58
1
For future readers, do not rely on thehref
attribute, it is unresolved and can contain things like../
meaning up one directory. Use the native property instead, likethis.href
.
– Walf
Aug 4 '16 at 0:53
3
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 '16 at 3:18
|
show 10 more comments
You can also use the lastIndexOf() function to locate the last occurrence of the /
character in your URL, then the substr() function to return the substring starting from that location:
window.alert(this.href.substr(this.href.lastIndexOf('/') + 1));
That way, you'll avoid creating an array containing all your URL segments, as split()
does.
2
@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
7
But if the url was become likeadmin/store/tour/-1/
so it's will be''
string?
– Set Kyar Wa Lar
Aug 20 '14 at 8:39
1
@Set, nicer maybe, slower surely.
– Frédéric Hamidi
Aug 20 '14 at 8:58
1
For future readers, do not rely on thehref
attribute, it is unresolved and can contain things like../
meaning up one directory. Use the native property instead, likethis.href
.
– Walf
Aug 4 '16 at 0:53
3
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 '16 at 3:18
|
show 10 more comments
You can also use the lastIndexOf() function to locate the last occurrence of the /
character in your URL, then the substr() function to return the substring starting from that location:
window.alert(this.href.substr(this.href.lastIndexOf('/') + 1));
That way, you'll avoid creating an array containing all your URL segments, as split()
does.
You can also use the lastIndexOf() function to locate the last occurrence of the /
character in your URL, then the substr() function to return the substring starting from that location:
window.alert(this.href.substr(this.href.lastIndexOf('/') + 1));
That way, you'll avoid creating an array containing all your URL segments, as split()
does.
edited Sep 27 '16 at 8:01
answered Jan 21 '11 at 11:18
Frédéric HamidiFrédéric Hamidi
207k31394419
207k31394419
2
@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
7
But if the url was become likeadmin/store/tour/-1/
so it's will be''
string?
– Set Kyar Wa Lar
Aug 20 '14 at 8:39
1
@Set, nicer maybe, slower surely.
– Frédéric Hamidi
Aug 20 '14 at 8:58
1
For future readers, do not rely on thehref
attribute, it is unresolved and can contain things like../
meaning up one directory. Use the native property instead, likethis.href
.
– Walf
Aug 4 '16 at 0:53
3
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 '16 at 3:18
|
show 10 more comments
2
@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
7
But if the url was become likeadmin/store/tour/-1/
so it's will be''
string?
– Set Kyar Wa Lar
Aug 20 '14 at 8:39
1
@Set, nicer maybe, slower surely.
– Frédéric Hamidi
Aug 20 '14 at 8:58
1
For future readers, do not rely on thehref
attribute, it is unresolved and can contain things like../
meaning up one directory. Use the native property instead, likethis.href
.
– Walf
Aug 4 '16 at 0:53
3
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 '16 at 3:18
2
2
@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
@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
7
7
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 8:39
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 8:39
1
1
@Set, nicer maybe, slower surely.
– Frédéric Hamidi
Aug 20 '14 at 8:58
@Set, nicer maybe, slower surely.
– Frédéric Hamidi
Aug 20 '14 at 8:58
1
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 4 '16 at 0:53
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 4 '16 at 0:53
3
3
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 '16 at 3:18
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 '16 at 3:18
|
show 10 more comments
var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
console.log(lastSegment);
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 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 '16 at 23:46
9
This won't work if the url ends with a "/" i.e.http://mywebsite/folder/file/
– Peter Ludlow
Feb 25 '16 at 4:40
add a comment |
var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
console.log(lastSegment);
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 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 '16 at 23:46
9
This won't work if the url ends with a "/" i.e.http://mywebsite/folder/file/
– Peter Ludlow
Feb 25 '16 at 4:40
add a comment |
var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
console.log(lastSegment);
var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
console.log(lastSegment);
var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
console.log(lastSegment);
var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
console.log(lastSegment);
edited Jun 24 '17 at 17:12


Chris Happy
4,5631933
4,5631933
answered Oct 28 '12 at 11:35
Tim van OostromTim van Oostrom
1,347195
1,347195
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 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 '16 at 23:46
9
This won't work if the url ends with a "/" i.e.http://mywebsite/folder/file/
– Peter Ludlow
Feb 25 '16 at 4:40
add a comment |
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 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 '16 at 23:46
9
This won't work if the url ends with a "/" i.e.http://mywebsite/folder/file/
– Peter Ludlow
Feb 25 '16 at 4:40
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 7:33
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 7:33
1
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
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
9
9
This won't work if the url ends with a "/" i.e.
http://mywebsite/folder/file/
– Peter Ludlow
Feb 25 '16 at 4:40
This won't work if the url ends with a "/" i.e.
http://mywebsite/folder/file/
– Peter Ludlow
Feb 25 '16 at 4:40
add a comment |
window.location.pathname.split("/").pop()
simple and easy. Thanks.
– krezaeim
Sep 24 '18 at 18:01
Perfect and tidy, great
– Babak Habibi
Oct 11 '18 at 12:29
add a comment |
window.location.pathname.split("/").pop()
simple and easy. Thanks.
– krezaeim
Sep 24 '18 at 18:01
Perfect and tidy, great
– Babak Habibi
Oct 11 '18 at 12:29
add a comment |
window.location.pathname.split("/").pop()
window.location.pathname.split("/").pop()
answered Nov 21 '16 at 16:56
Dblock247Dblock247
1,44032340
1,44032340
simple and easy. Thanks.
– krezaeim
Sep 24 '18 at 18:01
Perfect and tidy, great
– Babak Habibi
Oct 11 '18 at 12:29
add a comment |
simple and easy. Thanks.
– krezaeim
Sep 24 '18 at 18:01
Perfect and tidy, great
– Babak Habibi
Oct 11 '18 at 12:29
simple and easy. Thanks.
– krezaeim
Sep 24 '18 at 18:01
simple and easy. Thanks.
– krezaeim
Sep 24 '18 at 18:01
Perfect and tidy, great
– Babak Habibi
Oct 11 '18 at 12:29
Perfect and tidy, great
– Babak Habibi
Oct 11 '18 at 12:29
add a comment |
Just another solution with regex.
var href = location.href;
console.log(href.match(/([^/]*)/*$/)[1]);
2
this works great if URL ends with /
– Shoaib Iqbal
Nov 14 '16 at 6:00
add a comment |
Just another solution with regex.
var href = location.href;
console.log(href.match(/([^/]*)/*$/)[1]);
2
this works great if URL ends with /
– Shoaib Iqbal
Nov 14 '16 at 6:00
add a comment |
Just another solution with regex.
var href = location.href;
console.log(href.match(/([^/]*)/*$/)[1]);
Just another solution with regex.
var href = location.href;
console.log(href.match(/([^/]*)/*$/)[1]);
answered Apr 20 '16 at 10:56


AvirtumAvirtum
253313
253313
2
this works great if URL ends with /
– Shoaib Iqbal
Nov 14 '16 at 6:00
add a comment |
2
this works great if URL ends with /
– Shoaib Iqbal
Nov 14 '16 at 6:00
2
2
this works great if URL ends with /
– Shoaib Iqbal
Nov 14 '16 at 6:00
this works great if URL ends with /
– Shoaib Iqbal
Nov 14 '16 at 6:00
add a comment |
Javascript has the function split associated to string object that can help you:
var url = "http://mywebsite/folder/file";
var array = url.split('/');
var lastsegment = array[array.length-1];
add a comment |
Javascript has the function split associated to string object that can help you:
var url = "http://mywebsite/folder/file";
var array = url.split('/');
var lastsegment = array[array.length-1];
add a comment |
Javascript has the function split associated to string object that can help you:
var url = "http://mywebsite/folder/file";
var array = url.split('/');
var lastsegment = array[array.length-1];
Javascript has the function split associated to string object that can help you:
var url = "http://mywebsite/folder/file";
var array = url.split('/');
var lastsegment = array[array.length-1];
answered Jan 21 '11 at 11:14
Fran VeronaFran Verona
4,12833981
4,12833981
add a comment |
add a comment |
Or you could use a regular expression:
alert(href.replace(/.*//, ''));
add a comment |
Or you could use a regular expression:
alert(href.replace(/.*//, ''));
add a comment |
Or you could use a regular expression:
alert(href.replace(/.*//, ''));
Or you could use a regular expression:
alert(href.replace(/.*//, ''));
answered Jan 21 '11 at 11:21
jasssonpetjasssonpet
1,8391215
1,8391215
add a comment |
add a comment |
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);
add a comment |
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);
add a comment |
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);
answered Jan 21 '11 at 11:14
acmeacme
9,96065699
9,96065699
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Jun 20 '13 at 13:10
IL55IL55
455613
455613
add a comment |
add a comment |
Building on Frédéric's answer using only javascript:
var url = document.URL
window.alert(url.substr(url.lastIndexOf('/') + 1));
add a comment |
Building on Frédéric's answer using only javascript:
var url = document.URL
window.alert(url.substr(url.lastIndexOf('/') + 1));
add a comment |
Building on Frédéric's answer using only javascript:
var url = document.URL
window.alert(url.substr(url.lastIndexOf('/') + 1));
Building on Frédéric's answer using only javascript:
var url = document.URL
window.alert(url.substr(url.lastIndexOf('/') + 1));
answered Jan 13 '15 at 18:02


PinchPinch
2,50052652
2,50052652
add a comment |
add a comment |
Also,
var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
add a comment |
Also,
var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
add a comment |
Also,
var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
Also,
var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
answered Jan 21 '11 at 11:18
naveennaveen
37k36138216
37k36138216
add a comment |
add a comment |
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()
add a comment |
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()
add a comment |
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()
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 '15 at 16:24
Jaboc83Jaboc83
12217
12217
add a comment |
add a comment |
// 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.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
var targetValue = loc.substr(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);
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('/')); }
– Allan Raquin
Aug 3 '16 at 13:53
Fails if slash insearch
orhash
.
– Walf
Aug 4 '16 at 0:42
add a comment |
// 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.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
var targetValue = loc.substr(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);
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('/')); }
– Allan Raquin
Aug 3 '16 at 13:53
Fails if slash insearch
orhash
.
– Walf
Aug 4 '16 at 0:42
add a comment |
// 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.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
var targetValue = loc.substr(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)
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.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
var targetValue = loc.substr(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);
edited Jun 16 '16 at 12:29


bleakgadfly
84321630
84321630
answered Jun 17 '15 at 19:19


raddevusraddevus
2,75433042
2,75433042
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('/')); }
– Allan Raquin
Aug 3 '16 at 13:53
Fails if slash insearch
orhash
.
– Walf
Aug 4 '16 at 0:42
add a comment |
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('/')); }
– Allan Raquin
Aug 3 '16 at 13:53
Fails if slash insearch
orhash
.
– Walf
Aug 4 '16 at 0:42
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('/')); }
– Allan Raquin
Aug 3 '16 at 13:53
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('/')); }
– Allan Raquin
Aug 3 '16 at 13:53
Fails if slash in
search
or hash
.– Walf
Aug 4 '16 at 0:42
Fails if slash in
search
or hash
.– Walf
Aug 4 '16 at 0:42
add a comment |
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);
Also want to add thatpathname
strips query parameters, buthref
does not.
– Max Heiber
Aug 3 '16 at 15:33
add a comment |
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);
Also want to add thatpathname
strips query parameters, buthref
does not.
– Max Heiber
Aug 3 '16 at 15:33
add a comment |
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);
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);
edited Aug 4 '16 at 0:48
answered Jan 21 '11 at 11:43
WalfWalf
4,43312242
4,43312242
Also want to add thatpathname
strips query parameters, buthref
does not.
– Max Heiber
Aug 3 '16 at 15:33
add a comment |
Also want to add thatpathname
strips query parameters, buthref
does not.
– Max Heiber
Aug 3 '16 at 15:33
Also want to add that
pathname
strips query parameters, but href
does not.– Max Heiber
Aug 3 '16 at 15:33
Also want to add that
pathname
strips query parameters, but href
does not.– Max Heiber
Aug 3 '16 at 15:33
add a comment |
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 last = new URL(href).pathname.split('/').pop();
console.log(last);
Output: 'boo'
add a comment |
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 last = new URL(href).pathname.split('/').pop();
console.log(last);
Output: 'boo'
add a comment |
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 last = new URL(href).pathname.split('/').pop();
console.log(last);
Output: 'boo'
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 last = new URL(href).pathname.split('/').pop();
console.log(last);
Output: 'boo'
edited Nov 19 '18 at 21:10
answered Aug 10 '18 at 23:27


Sebastian BarthSebastian Barth
1,60632537
1,60632537
add a comment |
add a comment |
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
Copied from this answer
add a comment |
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
Copied from this answer
add a comment |
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
Copied from this answer
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
Copied from this answer
edited May 23 '17 at 12:02
Community♦
11
11
answered Jan 14 '16 at 16:02
Roberto AlonsoRoberto Alonso
53445
53445
add a comment |
add a comment |
To get the last segment of your current window:
window.location.href.substr(window.location.href.lastIndexOf('/') +1)
add a comment |
To get the last segment of your current window:
window.location.href.substr(window.location.href.lastIndexOf('/') +1)
add a comment |
To get the last segment of your current window:
window.location.href.substr(window.location.href.lastIndexOf('/') +1)
To get the last segment of your current window:
window.location.href.substr(window.location.href.lastIndexOf('/') +1)
answered May 23 '17 at 10:31
developerdeveloper
1,125625
1,125625
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
edited Feb 21 '18 at 13:35


F0XS
1,25631119
1,25631119
answered Feb 21 '18 at 13:01


Nemanja SmiljanicNemanja Smiljanic
112
112
add a comment |
add a comment |
Returns the last segment, regardless of trailing slashes:
var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();
console.log(val);
add a comment |
Returns the last segment, regardless of trailing slashes:
var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();
console.log(val);
add a comment |
Returns the last segment, regardless of trailing slashes:
var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();
console.log(val);
Returns the last segment, regardless of trailing slashes:
var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();
console.log(val);
var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();
console.log(val);
var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();
console.log(val);
edited Oct 6 '18 at 16:47
answered Aug 21 '18 at 12:46


John DohertyJohn Doherty
1,141916
1,141916
add a comment |
add a comment |
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));
add a comment |
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));
add a comment |
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));
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 '18 at 12:34


JaisonJaison
1,89011825
1,89011825
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
edited Jul 24 '18 at 4:07
answered Jul 24 '18 at 3:45
DinidinizDinidiniz
17819
17819
add a comment |
add a comment |
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);
add a comment |
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);
add a comment |
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);
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 '18 at 14:49


Veysi YILDIZVeysi YILDIZ
212
212
add a comment |
add a comment |
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:
[^/]+[/]?$
add a comment |
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:
[^/]+[/]?$
add a comment |
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:
[^/]+[/]?$
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 '18 at 12:40
user9628338
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4758103%2flast-segment-of-url%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Below is my working java script solution.Hope it helps. stackoverflow.com/a/38370175/610951
– Ravi
Jul 14 '16 at 9:19