我如何得到一个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的“文件”部分?
当前回答
这就是塞巴斯蒂安·巴斯的答案。
如果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);
}
其他回答
你可以先删除末尾的/,然后获取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);
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));
使用本机pathname属性,因为它是最简单的,并且已经被浏览器解析和解析过了。$(this).attr("href")可以返回类似../..这样就不会得到正确的结果。
如果你需要保留搜索和哈希(例如foo?Bar #baz from http://quux.com/path/to/foo?bar#baz)使用这个:
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);
仅使用javascript构建Frédéric的答案:
var url = document.URL
window.alert(url.substr(url.lastIndexOf('/') + 1));
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
抄自这个答案
同时,
var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);