最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Match Url path without query string - Stack Overflow

programmeradmin1浏览0评论

I would like to match a path in a Url, but ignoring the querystring. The regex should include an optional trailing slash before the querystring.

Example urls that should give a valid match:

/path/?a=123&b=123

/path?a=123&b=123

So the string '/path' should match either of the above urls.

I have tried the following regex: (/path[^?]+).*

But this will only match urls like the first example above: /path/?a=123&b=123

Any idea how i would go about getting it to match the second example without the trailing slash as well?

Regex is a requirement.

I would like to match a path in a Url, but ignoring the querystring. The regex should include an optional trailing slash before the querystring.

Example urls that should give a valid match:

/path/?a=123&b=123

/path?a=123&b=123

So the string '/path' should match either of the above urls.

I have tried the following regex: (/path[^?]+).*

But this will only match urls like the first example above: /path/?a=123&b=123

Any idea how i would go about getting it to match the second example without the trailing slash as well?

Regex is a requirement.

Share Improve this question edited Jun 6, 2015 at 19:34 Brad 163k55 gold badges377 silver badges552 bronze badges asked Oct 27, 2013 at 21:27 JCoder23JCoder23 5511 gold badge4 silver badges17 bronze badges 1
  • (/path[?]+|/path/[?]+).* – keenthinker Commented Oct 27, 2013 at 21:40
Add a comment  | 

2 Answers 2

Reset to default 9

No need for regexp:

url.split("?")[0];

If you really need it, then try this:

\/path\?*.*

EDIT Actually the most precise regexp should be:

^(\/path)(\/?\?{0}|\/?\?{1}.*)$

because you want to match either /path or /path/ or /path?something or /path/?something and nothing else. Note that ? means "at most one" while \? means a question mark.

BTW: What kind of routing library does not handle query strings?? I suggest using something else.

http://jsfiddle.net/bJcX3/

var re = /(\/?[^?]*?)\?.*/;

var p1 = "/path/to/something/?a=123&b=123";
var p2 = "/path/to/something/else?a=123&b=123";

var p1_matches = p1.match(re);
var p2_matches = p2.match(re);

document.write(p1_matches[1] + "<br>");
document.write(p2_matches[1] + "<br>");
发布评论

评论列表(0)

  1. 暂无评论