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(\
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
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);
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 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.
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.
window.location.pathname.split("/").pop()