Alex Rivera | Logout

Last segment of URL with JavaScript

Asked 2011-01-21T11:11:57.630
330

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?

Edit
Report

3 Answers

484

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.

answered 2011-01-21T11:18:53.400
9
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);
answered 2011-01-21T11:14:53.913
3

Also,

var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
answered 2011-01-21T11:18:34.280

Your Answer