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

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

如果url为

http://mywebsite/folder/file

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


当前回答

我相信在执行substring之前删除尾部斜杠('/')会更安全。因为我的场景中有一个空字符串。

window.alert((window.location.pathname).replace(/\/$/, "").substr((window.location.pathname.replace(/\/$/, "")).lastIndexOf('/') + 1));

其他回答

你也可以使用lastIndexOf()函数来定位URL中/字符最后出现的位置,然后使用substring()函数返回从该位置开始的子字符串:

console.log(this.href.substring(this.href.lastIndexOf('/') + 1));

这样,就可以避免像split()那样创建一个包含所有URL段的数组。

如果您不担心使用split生成额外的元素,那么filter可以处理您提到的尾随斜杠的问题(假设您有浏览器支持filter)。

url.split('/').filter(function (s) { return !!s }).pop()
// Store original location in loc like: http://test.com/one/ (ending slash)
var loc = location.href; 
// If the last char is a slash trim it, otherwise return the original loc
loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substring(0,loc.length-1) : loc.substring(0,loc.lastIndexOf('/'));
var targetValue = loc.substring(loc.lastIndexOf('/') + 1);

targetValue = 1

如果你的url看起来像:

http://test.com/one/

or

http://test.com/one

or

http://test.com/one/index.htm

然后loc最终看起来像: http://test.com/one

现在,因为您需要最后一项,所以运行下一步来加载最初需要的值(targetValue)。

var targetValue = loc.substr(loc.lastIndexOf('/') + 1);

// Store original location in loc like: http://test.com/one/ (ending slash) let loc = "http://test.com/one/index.htm"; console.log("starting loc value = " + loc); // If the last char is a slash trim it, otherwise return the original loc loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substring(0,loc.length-1) : loc.substring(0,loc.lastIndexOf('/')); let targetValue = loc.substring(loc.lastIndexOf('/') + 1); console.log("targetValue = " + targetValue); console.log("loc = " + loc);

如果路径很简单,仅由简单的路径元素组成,则其他答案可能有效。但是当它也包含查询参数时,它们就会中断。

最好使用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来说,有一个可用的腻子(如果你在乎的话)。

我使用regex和split:

var last_path = location.href.match(/。/ ((\ w)) /) [1] .split(“#”)[0].split(“?”)[0]

最后它将忽略# ?& /结束url,这种情况经常发生。例子:

https://cardsrealm.com/profile/cardsRealm -> Returns cardsRealm

https://cardsrealm.com/profile/cardsRealm / hello ->再turns cardsRealm

https://cardsrealm.com/profile/cardsRealm?hello ->再动画cardsRealm

https://cardsrealm.com/profile/cardsRealm/ -> Returns cardsRealm