javascript 正则表达式将特定 URL 与查询字符串匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18520736/
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 12:15:37  来源:igfitidea点击:

Regex to Match Specific URL with Query String

javascriptregex

提问by Sam G. Daniel

Hi I'm trying to match a specific URL that allows for query strings. Basically I need the following to happen:

嗨,我正在尝试匹配允许查询字符串的特定 URL。基本上我需要发生以下事情:

  • http://some.test.domain.com- Pass
  • http://some.test.domain.com/- Pass
  • http://some.test.domain.com/home- Pass
  • http://some.test.domain.com/?id=999- Pass
  • http://some.test.domain.com/home?id=888&rt=000- Pass
  • http://some.test.domain.com/other- Fail
  • http://some.test.domain.com/another?id=999- Fail
  • http://some.test.domain.com- 经过
  • http://some.test.domain.com/- 经过
  • http://some.test.domain.com/home- 经过
  • http://some.test.domain.com/?id=999- 经过
  • http://some.test.domain.com/home?id=888&rt=000- 经过
  • http://some.test.domain.com/other- 失败
  • http://some.test.domain.com/another?id=999- 失败

Here is what I have so far:

这是我到目前为止所拥有的:

var pattern = new RegExp('^(https?:\/\/some\.test\.domain\.com(\/{0,1}|\/home{0,1}))$');
if (pattern.test(window.location.href)){
    console.log('yes');   
}

The above code only works for the first three and not for the query strings. Any help would be appreciated. Thanks.

上面的代码只适用于前三个而不适用于查询字符串。任何帮助,将不胜感激。谢谢。

采纳答案by p.s.w.g

A pattern like this should work (at least for your specific domain)

这样的模式应该有效(至少对于您的特定域)

/^http:\/\/some\.test\.domain\.com(\/(home)?(\?.*)?)?$/

This will match a literal http://some.test.domain.comoptionally followed by all of a literal /, optionally followed by a literal home, optionally followed by a literal ?and any number of other characters.

这将匹配一个http://some.test.domain.com可选的文本/,后跟所有的文本,可选的后跟一个文本home,可选的后跟一个文本?和任意数量的其他字符。

You can test it here

你可以在这里测试

回答by Thomas Orozco

Don't use a Regex, use an URL parser. You could use purl

不要使用正则表达式,使用 URL 解析器。你可以用purl

Then, you'll do:

然后,您将执行以下操作:

url = "http://some.test.domain.com/home" // Or any other
purl(url).attr('path')  // is equal to "home" here.

You'll just need to check .attr('path')against your accepted paths (seemingly "", "/", and "home").

您只需要检查.attr('path')您接受的路径(似乎"""/"、 和"home")。



Here's some sample output:

这是一些示例输出:

purl("http://some.test.domain.com/?qs=1").attr('path')
"/"
purl("http://some.test.domain.com/other").attr("path")
"/other"
purl("http://some.test.domain.com/home").attr("path")
"/home"