如果我有以下内容:
example.com/test1
example.com/test1/
example.com/photo/test1
example.com/photo/category/test1/
(你明白了)
如何在jquery中加载test1作为加载变量?
window.location.pathname
为我提供了整个/照片/类别/ test1 /不仅是test1
非常感谢您的时间和帮助
答案 0 :(得分:0)
如果您想查找路径名的最后一部分,我想以下内容将起作用:
var path = window.location.pathname.split('/');
path = path.filter(function(x){return x!='';});
var last_path = path[path.length - 1]
答案 1 :(得分:0)
var parts = "example.com/photo/category/test1/".split('/')
var url = parts[parts.length - 1] ? parts[parts.length - 1] : parts[parts.length - 2];
(?:
负责最后/
)
答案 2 :(得分:0)
这是一个将提取最后一个路径元素的函数:
function getLastSegmentOfPath(url) {
var matches = url.match(/\/([^\/]+)\/?$/);
if (matches) {
return matches[1];
}
return null;
}
var endPath = getLastSegmentOfPath(window.location.href);
工作测试用例和演示:http://jsfiddle.net/jfriend00/9GXSZ/
正则表达式的工作原理如下:
\/ match a forward slash
() separately capture what is in the parens so we can extract just that part of the match
[^\/]+ match one or more chars that is not a slash
\/?$ match an optional forward slash followed the the end of the string
在正则表达式结果中(这是一个数组):
matches[0] is everything that matches the regex
matches[1] is what is in the first parenthesized group (what we're after here)
答案 3 :(得分:0)
您可以使用javascripts lastIndexOf
和substr
函数:
var url = window.location.pathname;
var index = url.lastIndexOf("/");
var lastbit = url.substr(index);
这是get的URL,找到最后/
的位置,并在此位置后返回所有内容。
修改(见评论): 要排除尾部斜杠(例如: category / test / ),并使用第一个斜杠:
var url = window.location.pathname;
var index = url.lastIndexOf("/");
var lastbit = url.substr(index);
if (lastbit == "/"){
url = url.slice(0, - 1);
index = url.lastIndexOf("/");
lastbit = url.substr(index);
}
lastbit = lastbit.substring(1);