我如何得到一个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的“文件”部分?
当前回答
仅使用javascript构建Frédéric的答案:
var url = document.URL
window.alert(url.substr(url.lastIndexOf('/') + 1));
其他回答
一种避免查询参数的方法
const urlString = "https://stackoverflow.com/last-segment?param=123" const url =新的url (urlString); url。搜索= "; const lastSegment = url.pathname.split('/').pop(); console.log (lastSegment)
如果url为http://localhost/madukaonline/shop.php?shop=79
console.log (location.search);将带来?shop=79
最简单的方法是使用location。search
你可以在这里查找更多信息 这里
获取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>');
});
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);
仅使用javascript构建Frédéric的答案:
var url = document.URL
window.alert(url.substr(url.lastIndexOf('/') + 1));