我如何得到一个url的最后一段?我有下面的脚本,显示点击锚标记的完整url:

$(".tag_name_goes_here").live('click', function(event)
{
    event.preventDefault();  
    alert($(this).attr("href"));
});

如果url为

http://mywebsite/folder/file

我如何才能让它在警告框中显示url的“文件”部分?


当前回答

window.location.pathname.split("/").pop()

其他回答

获取当前窗口的最后一段:

window.location.href.substr(window.location.href.lastIndexOf('/') +1)

更新raddevus答案:

var loc = window.location.href;
loc = loc.lastIndexOf('/') == loc.length - 1 ? loc.substr(0, loc.length - 1) : loc.substr(0, loc.length + 1);
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);

打印url的最后一个路径为字符串:

test.com/path-name = path-name

test.com/path-name/ = path-name

你也可以使用lastIndexOf()函数来定位URL中/字符最后出现的位置,然后使用substring()函数返回从该位置开始的子字符串:

console.log(this.href.substring(this.href.lastIndexOf('/') + 1));

这样,就可以避免像split()那样创建一个包含所有URL段的数组。

你可以先删除末尾的/,然后获取url的最后一部分

let locationLastPart = window.location.pathname
if (locationLastPart.substring(locationLastPart.length-1) == "/") {
  locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
}
locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);

仅使用javascript构建Frédéric的答案:

var url = document.URL

window.alert(url.substr(url.lastIndexOf('/') + 1));