我如何得到一个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的“文件”部分?
当前回答
我知道,已经太迟了,但对于其他人来说: 我强烈推荐使用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
其他回答
获取URL最后一段删除(-)和(/)的最佳方法
jQuery(document).ready(function(){
var path = window.location.pathname;
var parts = path.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
lastSegment = lastSegment.replace('-',' ').replace('-',' ');
jQuery('.archive .filters').before('<div class="product_heading"><h3>Best '+lastSegment+' Deals </h3></div>');
});
更新raddevus答案:
var loc = window.location.href;
loc = loc.lastIndexOf('/') == loc.length - 1 ? loc.substr(0, loc.length - 1) : loc.substr(0, loc.length + 1);
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
打印url的最后一个路径为字符串:
test.com/path-name = path-name
test.com/path-name/ = path-name
返回最后一段,不考虑后面的斜杠:
瓦尔瓦尔= http://mywebsite/folder/file//’。分裂(' / ')。布尔(过滤器)pop (); 控制台日志(val);
我知道它是旧的,但如果你想从一个URL得到这个,你可以简单地使用:
document.location.pathname.substring(document.location.pathname.lastIndexOf('/.') + 1);
document.location.pathname从当前URL获取路径名。 获取下面Regex最后一次出现的索引,在我们的例子中是/..点表示任意字符,因此,如果/是URL上的最后一个字符,则不算数。 Substring将截断两个索引之间的字符串。
这就是塞巴斯蒂安·巴斯的答案。
如果href是你正在解析的变量,new URL会抛出TypeError,所以为了安全起见,你应该尝试- catch
try{
const segments = new URL(href).pathname.split('/');
const last = segments.pop() || segments.pop(); // Handle potential trailing slash
console.log(last);
}catch (error){
//Uups, href wasn't a valid URL (empty string or malformed URL)
console.log('TypeError ->',error);
}