我如何得到一个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的“文件”部分?
当前回答
如果您不担心使用split生成额外的元素,那么filter可以处理您提到的尾随斜杠的问题(假设您有浏览器支持filter)。
url.split('/').filter(function (s) { return !!s }).pop()
其他回答
Var部分= 'http://mywebsite/folder/file'.split('/'); var lastSegment = parts.pop() || parts.pop();//处理潜在的尾随斜杠 console.log (lastSegment);
Javascript有与字符串对象相关联的函数split,可以帮助你:
const url = "http://mywebsite/folder/file";
const array = url.split('/');
const lastsegment = array[array.length-1];
我知道它是旧的,但如果你想从一个URL得到这个,你可以简单地使用:
document.location.pathname.substring(document.location.pathname.lastIndexOf('/.') + 1);
document.location.pathname从当前URL获取路径名。 获取下面Regex最后一次出现的索引,在我们的例子中是/..点表示任意字符,因此,如果/是URL上的最后一个字符,则不算数。 Substring将截断两个索引之间的字符串。
使用RegEx获取最后一段
str.replace(/.*\/(\w+)\/?$/, '$1');
$1表示使用捕获组。使用RegEx (\w+)创建第一个组,然后将整个字符串替换为捕获组。
let str =“http://mywebsite/folder/ fill”; 让我们把它放在一起。$ / ' $ '); 游戏机。log (lastSegment);
如果url为http://localhost/madukaonline/shop.php?shop=79
console.log (location.search);将带来?shop=79
最简单的方法是使用location。search
你可以在这里查找更多信息 这里