我如何得到一个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最后一段删除(-)和(/)的最佳方法
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>');
});
其他回答
只是正则表达式的另一个解。
var href = location.href;
console.log(href.match(/([^\/]*)\/*$/)[1]);
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);
最短的方法如何获得URL最后一段与split(), filter()和pop()
函数getLastUrlSegment(url) { 返回新的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这')); console.log(getLastUrlSegment('https://x.com/last带空格的段'));
对我有用。
Javascript有与字符串对象相关联的函数split,可以帮助你:
const url = "http://mywebsite/folder/file";
const array = url.split('/');
const lastsegment = array[array.length-1];
如果您不担心使用split生成额外的元素,那么filter可以处理您提到的尾随斜杠的问题(假设您有浏览器支持filter)。
url.split('/').filter(function (s) { return !!s }).pop()