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

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

如果url为

http://mywebsite/folder/file

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


当前回答

更新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

其他回答

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

如果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);
}

更新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

我真的不知道regex是否是解决这个问题的正确方法,因为它真的会影响代码的效率,但下面的regex将帮助您获取最后一个段,即使URL后面跟着一个空的/,它仍然会给您最后一个段。我想出的正则表达式是:

[^\/]+[\/]?$

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

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

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

返回最后一段,不考虑后面的斜杠:

瓦尔瓦尔= http://mywebsite/folder/file//’。分裂(' / ')。布尔(过滤器)pop (); 控制台日志(val);