开发者

jQuery to parse our a part of a url path

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 ur开发者_运维知识库l.

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/


When you do this.href*= you're doing multiplication, and that's why you're getting not-a-number. It multiplies this.href by the string and assigns that to href.

If you mean to test whether the url starts with that string you can do it like this, no need for jQuery:

var start = 'http://example.com/community/';
if (url.substring(0, start.length) === start)){
  var category = url.split("community/");
  var lastPart = category[category.length - 1];
  return lastPart.split("/")[0];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜