我如何得到一个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的“文件”部分?
当前回答
// 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部分= 'http://mywebsite/folder/file'.split('/'); var lastSegment = parts.pop() || parts.pop();//处理潜在的尾随斜杠 console.log (lastSegment);
最短的方法如何获得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带空格的段'));
对我有用。
你可以用简单的路径(w/0)查询字符串等来做到这一点。
虽然可能过于复杂,可能不是高性能的,但我想使用reduce是为了它的乐趣。
"/foo/bar/"
.split(path.sep)
.filter(x => x !== "")
.reduce((_, part, i, arr) => {
if (i == arr.length - 1) return part;
}, "");
在路径分隔符上拆分字符串。 过滤掉空字符串路径部分(这可能发生在路径的末尾斜杠)。 将路径部分数组减少到最后一个。
获取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 urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);