我如何得到一个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的“文件”部分?
当前回答
只是正则表达式的另一个解。
var href = location.href;
console.log(href.match(/([^\/]*)\/*$/)[1]);
其他回答
window.location.pathname.split("/").pop()
我知道它是旧的,但如果你想从一个URL得到这个,你可以简单地使用:
document.location.pathname.substring(document.location.pathname.lastIndexOf('/.') + 1);
document.location.pathname从当前URL获取路径名。 获取下面Regex最后一次出现的索引,在我们的例子中是/..点表示任意字符,因此,如果/是URL上的最后一个字符,则不算数。 Substring将截断两个索引之间的字符串。
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
抄自这个答案
Javascript有与字符串对象相关联的函数split,可以帮助你:
const url = "http://mywebsite/folder/file";
const array = url.split('/');
const lastsegment = array[array.length-1];
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);