javascript 匹配不带查询字符串的 Url 路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19623808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:13:36  来源:igfitidea点击:

Match Url path without query string

javascriptregex

提问by JCoder23

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.

我想匹配 Url 中的路径,但忽略查询字符串。正则表达式应该在查询字符串之前包含一个可选的尾部斜杠。

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.

所以字符串 '/path' 应该匹配上述任一网址。

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

我尝试了以下正则表达式: (/path[^?]+).*

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

但这只会匹配上面第一个示例的网址: /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.

正则表达式是一项要求。

采纳答案by freakish

No need for regexp:

不需要正则表达式:

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

If you really need it, then try this:

如果你真的需要它,那么试试这个:

\/path\?*.*

EDITActually the most precise regexp should be:

编辑实际上最精确的正则表达式应该是:

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

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

因为你想匹配/pathor/path//path?somethingor/path/?something并且没有别的。请注意,这?意味着“最多一个”,而\?意味着一个问号。

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

BTW:什么样的路由库不处理查询字符串??我建议使用其他东西。

回答by Kevin Collins

http://jsfiddle.net/bJcX3/

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>");