jQuery to parse our a part of a url path

前端 未结 2 724
醉梦人生
醉梦人生 2021-01-28 22:41

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.

2条回答
  •  爱一瞬间的悲伤
    2021-01-28 23:34

    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/

提交回复
热议问题