检查当前 URL,即使有 URL 参数也返回 true
Check for current URL, return true even if there are URL arguments
>我正在检查URL中非常具体的模式,以便仅在正确类型的页面上执行一组代码。目前,我有这样的东西:
/^http:'/'/www'.example'.com'/(?:example'/[^'/]+'/?)?$/;
因此,它将返回true
example.com
和example.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).
/
相关文章:
- 通过Javascript将HTML中的电话号码与URL参数进行交换
- 如何使用Javascript从URL参数中自动填充文本字段
- 如何将Google Analytics配置为将URL参数作为单个页面进行跟踪
- 在url参数javascript中存储键值对列表
- backbone.js-映射标准url参数-使用多个参数
- 将URL参数传递给ui sref
- Javascript从字符串中剥离所有url参数
- Javascript/jQuery获取所有url参数并添加/更改一个参数
- 在页面加载完成之前,使用URL参数运行JavaScript
- 使用Javascript获取URL参数
- 如何在 JavaScript 中解析 URL 参数
- 主干.js将 url 参数传递给集合
- 谷歌应用脚本中的 UrlFetchApp.fetch 删除 url 参数
- 通过javascript将url参数传递到多个不同的href链接中
- 角度 1 - 获取当前 URL 参数
- 使用jquery获取url参数
- 在Javascript代码中插入URL参数
- Angular 2:HTTP Post Request,带有URL参数和正文类型参数
- 限制与AngularJS状态匹配的动态URL参数的最佳方式
- 如何根据URL参数生成包含JS内容的单个HTML文件