我如何得到一个url的最后一段?我有下面的脚本,显示点击锚标记的完整url:

$(".tag_name_goes_here").live('click', function(event)
{
    event.preventDefault();  
    alert($(this).attr("href"));
});

如果url为

http://mywebsite/folder/file

我如何才能让它在警告框中显示url的“文件”部分?


当前回答

最短的方法如何获得URL最后一段与split(), filter()和pop()

函数getLastUrlSegment(url) { 返回新的URL(URL).pathname.split('/').filter(Boolean).pop(); } console.log (getLastUrlSegment (window.location.href)); console.log (getLastUrlSegment (' https://x.com/boo ')); console.log (getLastUrlSegment (' https://x.com/boo/ ')); console.log (getLastUrlSegment (' https://x.com/boo?q=foo&s=bar=aaa ')); console.log (getLastUrlSegment (https://x.com/boo?q=foo这')); console.log(getLastUrlSegment('https://x.com/last带空格的段'));

对我有用。

其他回答

这就是塞巴斯蒂安·巴斯的答案。

如果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);
}
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);

最短的方法如何获得URL最后一段与split(), filter()和pop()

函数getLastUrlSegment(url) { 返回新的URL(URL).pathname.split('/').filter(Boolean).pop(); } console.log (getLastUrlSegment (window.location.href)); console.log (getLastUrlSegment (' https://x.com/boo ')); console.log (getLastUrlSegment (' https://x.com/boo/ ')); console.log (getLastUrlSegment (' https://x.com/boo?q=foo&s=bar=aaa ')); console.log (getLastUrlSegment (https://x.com/boo?q=foo这')); console.log(getLastUrlSegment('https://x.com/last带空格的段'));

对我有用。

更新raddevus答案:

var loc = window.location.href;
loc = loc.lastIndexOf('/') == loc.length - 1 ? loc.substr(0, loc.length - 1) : loc.substr(0, loc.length + 1);
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);

打印url的最后一个路径为字符串:

test.com/path-name = path-name

test.com/path-name/ = path-name

Javascript有与字符串对象相关联的函数split,可以帮助你:

const url = "http://mywebsite/folder/file";
const array = url.split('/');

const lastsegment = array[array.length-1];