jQuery解析我们的一部分url路径 [英] jQuery to parse our a part of a url path

查看:89
本文介绍了jQuery解析我们的一部分url路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析长url,并设置一个变量(类别)等于路径中 / folders / 之一。



例如,一个网址是

http://example.com/community/home/whatever.html



我需要设置变量等于任何文件夹路径出现在 / home / 在这个网址中。



我已经知道/ community /后面会出现什么内容,但是网址转换为NaN并且链接不起作用。我认为我没有走上正轨。

  if($(this.href * ='http:// example .com / community /')){

var category = url.split(community /);

alert(category [category.length - 1]);


想法?



TIA。

解决方案

您可以使用正则表达式在/ 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/

这篇关于jQuery解析我们的一部分url路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆