osh*_*nen 213 javascript jquery
如何获取网址的最后一段?我有以下脚本显示单击的锚标记的完整URL:
$(".tag_name_goes_here").live('click', function(event)
{
event.preventDefault();
alert($(this).attr("href"));
});
Run Code Online (Sandbox Code Playgroud)
如果网址是
http://mywebsite/folder/file
Run Code Online (Sandbox Code Playgroud)
我如何才能在警告框中显示网址的"文件"部分?
Fré*_*idi 336
您还可以使用lastIndexOf()函数来查找/URL中最后一次出现的字符,然后使用substr()函数返回从该位置开始的子字符串:
console.log(this.href.substring(this.href.lastIndexOf('/') + 1));
Run Code Online (Sandbox Code Playgroud)
这样,您就可以避免创建包含所有网段的数组split().
小智 138
var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
console.log(lastSegment);Run Code Online (Sandbox Code Playgroud)
Dbl*_*247 67
window.location.pathname.split("/").pop()
Run Code Online (Sandbox Code Playgroud)
Avi*_*tum 27
只是另一种正则表达式的解决方案.
var href = location.href;
console.log(href.match(/([^\/]*)\/*$/)[1]);
Run Code Online (Sandbox Code Playgroud)
Fra*_*ona 18
Javascript具有与字符串对象相关联的函数split,可以帮助您:
var url = "http://mywebsite/folder/file";
var array = url.split('/');
var lastsegment = array[array.length-1];
Run Code Online (Sandbox Code Playgroud)
小智 17
如何使用,和获取URL最后一段的最短方法split()filter()pop()
function getLastUrlSegment(url) {
return new 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#this'));
console.log(getLastUrlSegment('https://x.com/last segment with spaces'));Run Code Online (Sandbox Code Playgroud)
对我有用。
Seb*_*rth 11
如果路径很简单(仅由简单路径元素组成),则其他答案可能会起作用。但是,当它还包含查询参数时,它们就会中断。
最好为此使用URL对象,以获得更可靠的解决方案。它是对当前URL的解析解释:
输入: const href = 'https://stackoverflow.com/boo?q=foo&s=bar'
const last = new URL(href).pathname.split('/').pop();
console.log(last);
Run Code Online (Sandbox Code Playgroud)
输出: 'boo'
这适用于所有常见的浏览器。只有我们垂死的IE不支持(并且不会)。对于IE,可以使用polyfills(如果您很在意的话)。
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);
Run Code Online (Sandbox Code Playgroud)
返回最后一段,无论尾部斜杠如何:
var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();
console.log(val);Run Code Online (Sandbox Code Playgroud)
我知道,为时已晚,但对于其他人:我强烈建议使用PURL jquery插件.PURL的动机是url也可以用'#'来分段(例如:angular.js链接),即url看起来像
http://test.com/#/about/us/
Run Code Online (Sandbox Code Playgroud)
要么
http://test.com/#sky=blue&grass=green
Run Code Online (Sandbox Code Playgroud)
使用PURL,您可以轻松决定(细分/细分)您想要获得的细分.
对于"经典"的最后一段你可以写:
var url = $.url('http://test.com/dir/index.html?key=value');
var lastSegment = url.segment().pop(); // index.html
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
222745 次 |
| 最近记录: |