Javascript 正则表达式检查 URL 是否包含一个单词且不包含另一个单词
如何检查 url 是否包含特定单词,同时检查它是否不包含单词?如果我尝试显示一个示例,效果会更好:
如果 URL 中包含“pan”一词,则执行某些操作,但当 URL 中包含“panini”一词时,请勿执行任何操作url:
if (/pan/.test(self.location.href) && (/panini/.test(self.location.href) == null) {...}
上面的第一部分工作正常,但是添加了第二部分帕尼尼部分,它当然行不通,有人有什么想法吗?
How can one check a url if it contains a specific word, but also check to see if it doesn't contain a word? Its better if I try and display an example:
Do something if the word 'pan' is in the URL, however do NOT do anything when the word 'panini' is in the url:
if (/pan/.test(self.location.href) && (/panini/.test(self.location.href) == null) {...}
The above first part works fine, but with the second panini part added it of course will not work, anyone have any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
test
返回一个布尔值,因此只需使用!
运算符:这可以简化为使用
indexOf
(应该更快):此外,单词的正则表达式测试可以使用单词边界,
\b
:test
returns a bool, so just use the!
operator:This could be simplified to use
indexOf
(should be faster):Additionally, a regex testing for a word can use a word boundary,
\b
:JavaScript 的
indexOf
可能会解决您的问题。JavaScript's
indexOf
might solve your problem.您可以按如下方式使用
indexOf
属性:You can use the
indexOf
property as follows:您还可以使用负向前视,JS 在所有主要浏览器中都支持。
/pan(?!ini)/
正则表达式匹配任何后面不跟“ini”的“pan”。You can also use negative lookahead, which JS supports in all major browsers.
The
/pan(?!ini)/
regex matches any "pan" not followed by "ini".