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

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

如果url为

http://mywebsite/folder/file

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


当前回答

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

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

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

其他回答

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

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

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

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

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

var pathname = window.location.pathname; // Returns path only
var url      = window.location.href;     // Returns full URL

抄自这个答案

var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);

你可以用简单的路径(w/0)查询字符串等来做到这一点。

虽然可能过于复杂,可能不是高性能的,但我想使用reduce是为了它的乐趣。

  "/foo/bar/"
    .split(path.sep)
    .filter(x => x !== "")
    .reduce((_, part, i, arr) => {
      if (i == arr.length - 1) return part;
    }, "");

在路径分隔符上拆分字符串。 过滤掉空字符串路径部分(这可能发生在路径的末尾斜杠)。 将路径部分数组减少到最后一个。