Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检查当前URL,即使有URL参数也返回true_Javascript_Regex - Fatal编程技术网

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

Javascript 检查当前URL,即使有URL参数也返回true,javascript,regex,Javascript,Regex,我正在检查URL中的一个非常特定的模式,以便一组代码只在正确类型的页面上执行。目前,我得到了如下信息: /^http:\/\/www.example\.com\/(?:example\/[^\/]+\/?)?$/ 因此,对于example.com和example.com/example/anythinghere/,它将返回true。但是,有时此网站会在URL末尾附加参数,如?postCount=25或其他内容,因此您可以得到: example.com/example/anythinghere/?

我正在检查URL中的一个非常特定的模式,以便一组代码只在正确类型的页面上执行。目前,我得到了如下信息:

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

因此,对于
example.com
example.com/example/anythinghere/
,它将返回
true
。但是,有时此网站会在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。

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

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

尝试以下正则表达式:

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

将我的评论升级为答案:

 /^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
  /
这里的主要问题是,您的需求(“后跟一个可选的querystring”)与您的regex(需要字符串结尾)不匹配。我们通过以下方式解决这个问题:

 /^    # 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).
  /

在最后一个之前放下
,将
$
更改为
(\?$)
(因此结尾看起来像
。[^\/]+\/)(\?$)
就像一个符咒!如果你想让它成为一个正式的答案,我很高兴表示适当的感谢。明天我会尝试一下,然后再给你回复!