我如何得到一个url的最后一段?我有下面的脚本,显示点击锚标记的完整url:
$(".tag_name_goes_here").live('click', function(event)
{
event.preventDefault();
alert($(this).attr("href"));
});
如果url为
http://mywebsite/folder/file
我如何才能让它在警告框中显示url的“文件”部分?
我如何得到一个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
其他回答
你也可以使用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);
我真的不知道regex是否是解决这个问题的正确方法,因为它真的会影响代码的效率,但下面的regex将帮助您获取最后一个段,即使URL后面跟着一个空的/,它仍然会给您最后一个段。我想出的正则表达式是:
[^\/]+[\/]?$
同时,
var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
如果您不担心使用split生成额外的元素,那么filter可以处理您提到的尾随斜杠的问题(假设您有浏览器支持filter)。
url.split('/').filter(function (s) { return !!s }).pop()