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

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

如果url为

http://mywebsite/folder/file

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


当前回答

我知道它是旧的,但如果你想从一个URL得到这个,你可以简单地使用:

document.location.pathname.substring(document.location.pathname.lastIndexOf('/.') + 1);

document.location.pathname从当前URL获取路径名。 获取下面Regex最后一次出现的索引,在我们的例子中是/..点表示任意字符,因此,如果/是URL上的最后一个字符,则不算数。 Substring将截断两个索引之间的字符串。

其他回答

Javascript有与字符串对象相关联的函数split,可以帮助你:

const url = "http://mywebsite/folder/file";
const array = url.split('/');

const lastsegment = array[array.length-1];

你可以先删除末尾的/,然后获取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);
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);

同时,

var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);

我真的不知道regex是否是解决这个问题的正确方法,因为它真的会影响代码的效率,但下面的regex将帮助您获取最后一个段,即使URL后面跟着一个空的/,它仍然会给您最后一个段。我想出的正则表达式是:

[^\/]+[\/]?$