我如何得到一个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的“文件”部分?
当前回答
同时,
var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
其他回答
我相信在执行substring之前删除尾部斜杠('/')会更安全。因为我的场景中有一个空字符串。
window.alert((window.location.pathname).replace(/\/$/, "").substr((window.location.pathname.replace(/\/$/, "")).lastIndexOf('/') + 1));
window.location.pathname.split("/").pop()
这就是塞巴斯蒂安·巴斯的答案。
如果href是你正在解析的变量,new URL会抛出TypeError,所以为了安全起见,你应该尝试- catch
try{
const segments = new URL(href).pathname.split('/');
const last = segments.pop() || segments.pop(); // Handle potential trailing slash
console.log(last);
}catch (error){
//Uups, href wasn't a valid URL (empty string or malformed URL)
console.log('TypeError ->',error);
}
你可以用简单的路径(w/0)查询字符串等来做到这一点。
虽然可能过于复杂,可能不是高性能的,但我想使用reduce是为了它的乐趣。
"/foo/bar/"
.split(path.sep)
.filter(x => x !== "")
.reduce((_, part, i, arr) => {
if (i == arr.length - 1) return part;
}, "");
在路径分隔符上拆分字符串。 过滤掉空字符串路径部分(这可能发生在路径的末尾斜杠)。 将路径部分数组减少到最后一个。
如果路径很简单,仅由简单的路径元素组成,则其他答案可能有效。但是当它也包含查询参数时,它们就会中断。
最好使用URL对象,以获得更健壮的解决方案。它是当前URL的解析解释:
输入: Const href = 'https://stackoverflow.com/boo?q=foo&s=bar'
const segments = new URL(href).pathname.split('/');
const last = segments.pop() || segments.pop(); // Handle potential trailing slash
console.log(last);
输出:“嘘”
这适用于所有常见的浏览器。只有我们垂死的IE不支持(也不会支持)。对于IE来说,有一个可用的腻子(如果你在乎的话)。