Javascript 正则表达式检查 URL 是否包含一个单词且不包含另一个单词

发布于 2024-12-02 07:37:38 字数 334 浏览 5 评论 0原文

如何检查 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

追我者格杀勿论 2024-12-09 07:37:38

test 返回一个布尔值,因此只需使用 ! 运算符:

if (/pan/.test(self.location.href) && !(/panini/.test(self.location.href))  {...}

这可以简化为使用 indexOf(应该更快):

if (self.location.href.indexOf("pan") > -1 && self.location.href.indexOf("panini") == -1)
{...}

此外,单词的正则表达式测试可以使用单词边界,\b

/\bpan\b/.test(self.location.href)
//Will match "pan", "pan and food", but not "panini"

test returns a bool, so just use the ! operator:

if (/pan/.test(self.location.href) && !(/panini/.test(self.location.href))  {...}

This could be simplified to use indexOf (should be faster):

if (self.location.href.indexOf("pan") > -1 && self.location.href.indexOf("panini") == -1)
{...}

Additionally, a regex testing for a word can use a word boundary, \b:

/\bpan\b/.test(self.location.href)
//Will match "pan", "pan and food", but not "panini"
柠檬 2024-12-09 07:37:38

JavaScript 的 indexOf 可能会解决您的问题。

var h=location.href;
if (h.indexOf("pan")>-1 && h.indexOf("panini")==-1) // do stuff

JavaScript's indexOf might solve your problem.

var h=location.href;
if (h.indexOf("pan")>-1 && h.indexOf("panini")==-1) // do stuff
你是我的挚爱i 2024-12-09 07:37:38

您可以按如下方式使用 indexOf 属性:

url = window.location.href;
if ((url.indexOf("pan") >= 0) && (url.indexOf("panini") < 0)

You can use the indexOf property as follows:

url = window.location.href;
if ((url.indexOf("pan") >= 0) && (url.indexOf("panini") < 0)
停顿的约定 2024-12-09 07:37:38

您还可以使用负向前视,JS 在所有主要浏览器中都支持。

if ((/pan(?!ini)/).test(myurl)) {

/pan(?!ini)/ 正则表达式匹配任何后面不跟“ini”的“pan”。

You can also use negative lookahead, which JS supports in all major browsers.

if ((/pan(?!ini)/).test(myurl)) {

The /pan(?!ini)/ regex matches any "pan" not followed by "ini".

小兔几 2024-12-09 07:37:38
var myurl = self.location.href;
if (myurl.indexOf("pan") != -1) && (myurl.indexOf("panini") == -1)
{
   //do something
}
var myurl = self.location.href;
if (myurl.indexOf("pan") != -1) && (myurl.indexOf("panini") == -1)
{
   //do something
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文