检查当前 URL,即使有 URL 参数也返回 true

Check for current URL, return true even if there are URL arguments

本文关键字:URL 参数 返回 true 检查      更新时间:2023-09-26

>我正在检查URL中非常具体的模式,以便仅在正确类型的页面上执行一组代码。目前,我有这样的东西:

/^http:'/'/www'.example'.com'/(?:example'/[^'/]+'/?)?$/;

因此,它将返回true example.comexample.com/example/anythinghere/。但是,有时该网站会在URL的末尾附加诸如?postCount=25之类的参数,因此您可以获得:

example.com/example/anythinghere/?postCount=25

因此,如果我将当前表达式放入条件中,如果有 URL 参数,它将返回 false。我如何最好地更改正则表达式以允许可选的 URL 参数通配符,以便如果有一个问号后跟任何其他信息,它将始终返回 true,如果省略它,它仍然会返回 true?

对于以下情况,它需要返回 true:

http://www.example.com/?argumentshere

http://www.example.com/example/anythinghere/?argumentshere

以及那些没有额外参数的相同 URL。

尝试以下正则表达式:

^http:'/'/www'.example'.com(?:'/example'/[^'/]+'/?)?'??.*$

正则表达式101演示

您可以构建不带参数的 URL,并将其与当前表达式进行比较。

location.protocol + '//' + location.host + location.pathname

如何在 JavaScript 中获取没有任何参数的 URL?

将我的评论升级为答案:

 /^http:'/'/www'.example'.com'/(?:example'/[^'/]+'/?)?$/;

手段:

 /^    # start of string
      http:'/'/www'.example'.com'/  #literal http://www.example.com/
      (?:           
         example'/[^'/]+'/? #followed by example/whatever (optionally closed by /)
      )?
      $ end-of-string
  /

这里的主要问题是您的要求("后跟一个可选的查询字符串")与您的正则表达式(需要字符串结尾)不匹配。我们通过以下方式解决它:

 /^    # start of string
      http:'/'/www'.example'.com'/  #literal http://www.example.com/
      (?:           
         example'/[^'/]+'/? #followed by example/whatever (optionally closed by /)
      )?
      ('?|$) followed by either an end-of-string (original), or a literal `?` (which in url context means the rest is a query string and not a path anymore).
  /