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?


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.


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

console.log(lastSegment);

正则表达式的另一个解决方案。

var href = location.href;
console.log(href.match(/([^/]*)/*$/)[1]);
链接地址: http://www.djcxy.com/p/70242.html

上一篇: 使用Jquery获取当前的URL

下一篇: URL的最后一部分