如果值有点,则正则表达式不应该匹配

问题描述 投票:0回答:2

我想检查一个变量是否在一组单词中的任何一个中。例如

'Guava'.match(/\b(apple|mango|orange)\b/ig);

以上不相符,这是正确的。

'AppleA'.match(/\b(apple|mango|orange)\b/ig)

这也不匹配。再次正确。

'Apple.A'.match(/\b(apple|mango|orange)\b/ig)

然而,这会返回一个匹配项,这不是我想要的。我该如何解决这个问题?

仅当值为

Apple
OR
apple
OR
mango
OR
mAngo
等时,我才想要匹配。

javascript regex
2个回答
2
投票

试试这个

'Apple.A'.match(/^(apple|mango|orange)$/ig)

enter image description here


0
投票

要检查一个字符串是否是 JavaScript 中的多个字符串之一,不区分大小写,可以使用

toLowerCase
方法将字符串转换为小写,并将其传递给多个字符串数组的
includes
方法进行检查:

console.log(['apple', 'mango', 'orange'].includes('Apple.A'.toLowerCase()));

© www.soinside.com 2019 - 2024. All rights reserved.