更新时间:2023-01-11 16:47:10
您可以使用正则表达式在/ community / p>
var url =http://www.example.com/community/whatever;
var category =;
var matches = url.match(/ \ / community\ /(.*)$/);
if(matches){
category = matches [1]; //whatever
}
工作示例: http://jsfiddle.net/jfriend00/BL4jm/
如果你想要在社区之后获得下一个路径段,并且在该段之后没有任何内容,那么您可以使用以下代码:
var url = http://www.example.com/community/whatever/more;
var category =;
var matches = url.match(/ \ / community\ /([^ \ /] +)/);
if(matches){
category = matches [1]; //whatever
} else {
//不匹配类别
}
Workkng这个例子在这里:http://jsfiddle.net/jfriend00/vrvbT/
I need to parse long urls and set a variable (category) equal to one of the /folders/
in the path.
For example, a url that is
http://example.com/community/home/whatever.html
I need to set the variable equal to whatever folder path comes after /home/
in that url.
I've got this to alert me with what comes after /community/, but then the url turns to NaN and the link doesnt work. I think I'm not on the right track.
if ($(this.href*='http://example.com/community/')){
var category = url.split("community/");
alert(category[category.length - 1]);
}
Thoughts?
TIA.
You can fetch everything after the "/community/" with a regular expression:
var url = "http://www.example.com/community/whatever";
var category = "";
var matches = url.match(/\/community\/(.*)$/);
if (matches) {
category = matches[1]; // "whatever"
}
Working example here: http://jsfiddle.net/jfriend00/BL4jm/
If you want to get only the next path segment after community and nothing after that segment, then you could use this:
var url = "http://www.example.com/community/whatever/more";
var category = "";
var matches = url.match(/\/community\/([^\/]+)/);
if (matches) {
category = matches[1]; // "whatever"
} else {
// no match for the category
}
Workikng example of this one here:http://jsfiddle.net/jfriend00/vrvbT/