我如何得到一个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的“文件”部分?
当前回答
你可以用简单的路径(w/0)查询字符串等来做到这一点。
虽然可能过于复杂,可能不是高性能的,但我想使用reduce是为了它的乐趣。
"/foo/bar/"
.split(path.sep)
.filter(x => x !== "")
.reduce((_, part, i, arr) => {
if (i == arr.length - 1) return part;
}, "");
在路径分隔符上拆分字符串。 过滤掉空字符串路径部分(这可能发生在路径的末尾斜杠)。 将路径部分数组减少到最后一个。
其他回答
我使用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
一种避免查询参数的方法
const urlString = "https://stackoverflow.com/last-segment?param=123" const url =新的url (urlString); url。搜索= "; const lastSegment = url.pathname.split('/').pop(); console.log (lastSegment)
window.location.pathname.split("/").pop()
或者你可以使用正则表达式:
alert(href.replace(/.*\//, ''));
我相信在执行substring之前删除尾部斜杠('/')会更安全。因为我的场景中有一个空字符串。
window.alert((window.location.pathname).replace(/\/$/, "").substr((window.location.pathname.replace(/\/$/, "")).lastIndexOf('/') + 1));