我如何得到一个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获取最后一段
str.replace(/.*\/(\w+)\/?$/, '$1');
$1表示使用捕获组。使用RegEx (\w+)创建第一个组,然后将整个字符串替换为捕获组。
let str =“http://mywebsite/folder/ fill”; 让我们把它放在一起。$ / ' $ '); 游戏机。log (lastSegment);
其他回答
你也可以使用lastIndexOf()函数来定位URL中/字符最后出现的位置,然后使用substring()函数返回从该位置开始的子字符串:
console.log(this.href.substring(this.href.lastIndexOf('/') + 1));
这样,就可以避免像split()那样创建一个包含所有URL段的数组。
// 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得到这个,你可以简单地使用:
document.location.pathname.substring(document.location.pathname.lastIndexOf('/.') + 1);
document.location.pathname从当前URL获取路径名。 获取下面Regex最后一次出现的索引,在我们的例子中是/..点表示任意字符,因此,如果/是URL上的最后一个字符,则不算数。 Substring将截断两个索引之间的字符串。
我真的不知道regex是否是解决这个问题的正确方法,因为它真的会影响代码的效率,但下面的regex将帮助您获取最后一个段,即使URL后面跟着一个空的/,它仍然会给您最后一个段。我想出的正则表达式是:
[^\/]+[\/]?$
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);