Last segment of URL

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)

If the url is

how do I only get it to display the “file” part of the url in the alert box?


Solution 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.

Solution 2:

var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop();  // handle potential trailing slash


Solution 3:


Solution 4:

Just another solution with regex.

var href = location.href;

Solution 5:

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];

Solution 6:

Or you could use a regular expression:

alert(href.replace(/.*\//, ''));