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

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

如果url为

http://mywebsite/folder/file

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


当前回答

Var部分= 'http://mywebsite/folder/file'.split('/'); var lastSegment = parts.pop() || parts.pop();//处理潜在的尾随斜杠 console.log (lastSegment);

其他回答

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

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

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

最短的方法如何获得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带空格的段'));

对我有用。

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

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

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