我如何得到一个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的“文件”部分?
当前回答
获取当前窗口的最后一段:
window.location.href.substr(window.location.href.lastIndexOf('/') +1)
其他回答
你也可以使用lastIndexOf()函数来定位URL中/字符最后出现的位置,然后使用substring()函数返回从该位置开始的子字符串:
console.log(this.href.substring(this.href.lastIndexOf('/') + 1));
这样,就可以避免像split()那样创建一个包含所有URL段的数组。
window.location.pathname.split("/").pop()
如果您不担心使用split生成额外的元素,那么filter可以处理您提到的尾随斜杠的问题(假设您有浏览器支持filter)。
url.split('/').filter(function (s) { return !!s }).pop()
如果url为http://localhost/madukaonline/shop.php?shop=79
console.log (location.search);将带来?shop=79
最简单的方法是使用location。search
你可以在这里查找更多信息 这里
我使用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