我如何得到一个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的“文件”部分?
当前回答
我真的不知道regex是否是解决这个问题的正确方法,因为它真的会影响代码的效率,但下面的regex将帮助您获取最后一个段,即使URL后面跟着一个空的/,它仍然会给您最后一个段。我想出的正则表达式是:
[^\/]+[\/]?$
其他回答
我相信在执行substring之前删除尾部斜杠('/')会更安全。因为我的场景中有一个空字符串。
window.alert((window.location.pathname).replace(/\/$/, "").substr((window.location.pathname.replace(/\/$/, "")).lastIndexOf('/') + 1));
使用RegEx获取最后一段
str.replace(/.*\/(\w+)\/?$/, '$1');
$1表示使用捕获组。使用RegEx (\w+)创建第一个组,然后将整个字符串替换为捕获组。
let str =“http://mywebsite/folder/ fill”; 让我们把它放在一起。$ / ' $ '); 游戏机。log (lastSegment);
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);
我知道,已经太迟了,但对于其他人来说: 我强烈推荐使用PURL jquery插件。PURL的动机是url也可以用“#”来分割(例如:angular.js links),即url可以看起来像
http://test.com/#/about/us/
or
http://test.com/#sky=blue&grass=green
使用PURL,您可以很容易地决定(segment/fsegment)您想要获得的段。
对于“经典”的最后一部分,你可以这样写:
var url = $.url('http://test.com/dir/index.html?key=value');
var lastSegment = url.segment().pop(); // index.html
仅使用javascript构建Frédéric的答案:
var url = document.URL
window.alert(url.substr(url.lastIndexOf('/') + 1));