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
Match Url path without query string
提问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 /path
or /path/
or /path?something
or /path/?something
and nothing else. Note that ?
means "at most one" while \?
means a question mark.
因为你想匹配/path
or/path/
或/path?something
or/path/?something
并且没有别的。请注意,这?
意味着“最多一个”,而\?
意味着一个问号。
BTW: What kind of routing library does not handle query strings?? I suggest using something else.
BTW:什么样的路由库不处理查询字符串??我建议使用其他东西。
回答by Kevin Collins
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>");