Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last segment of URL in 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?

like image 268
oshirowanen Avatar asked Jan 21 '11 11:01

oshirowanen


1 Answers

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.

like image 138
Frédéric Hamidi Avatar answered Oct 16 '22 16:10

Frédéric Hamidi