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

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

如果url为

http://mywebsite/folder/file

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


当前回答

我使用regex和split:

var last_path = location.href.match(/。/ ((\ w)) /) [1] .split(“#”)[0].split(“?”)[0]

最后它将忽略# ?& /结束url,这种情况经常发生。例子:

https://cardsrealm.com/profile/cardsRealm -> Returns cardsRealm

https://cardsrealm.com/profile/cardsRealm / hello ->再turns cardsRealm

https://cardsrealm.com/profile/cardsRealm?hello ->再动画cardsRealm

https://cardsrealm.com/profile/cardsRealm/ -> Returns cardsRealm

其他回答

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

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

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

如果您不担心使用split生成额外的元素,那么filter可以处理您提到的尾随斜杠的问题(假设您有浏览器支持filter)。

url.split('/').filter(function (s) { return !!s }).pop()
window.location.pathname.split("/").pop()

Var部分= 'http://mywebsite/folder/file'.split('/'); var lastSegment = parts.pop() || parts.pop();//处理潜在的尾随斜杠 console.log (lastSegment);

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

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