我如何得到一个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的“文件”部分?
当前回答
如果url为http://localhost/madukaonline/shop.php?shop=79
console.log (location.search);将带来?shop=79
最简单的方法是使用location。search
你可以在这里查找更多信息 这里
其他回答
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);
// 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);
只是正则表达式的另一个解。
var href = location.href;
console.log(href.match(/([^\/]*)\/*$/)[1]);
我相信在执行substring之前删除尾部斜杠('/')会更安全。因为我的场景中有一个空字符串。
window.alert((window.location.pathname).replace(/\/$/, "").substr((window.location.pathname.replace(/\/$/, "")).lastIndexOf('/') + 1));
如果url为http://localhost/madukaonline/shop.php?shop=79
console.log (location.search);将带来?shop=79
最简单的方法是使用location。search
你可以在这里查找更多信息 这里