如何使用RegExp检查字符串中是否包含单词

时间:2019-03-02 22:46:46

标签: javascript regex string

有一个字符串,我想测试字符串中是否包含多个单词,一种简单的方法是使用循环和include()方法,但是我想知道是否可以使用RegExp进行检查。它

例如,字符串为“我们可以以低于4000的价格累积它”,我需要检查该字符串是否包含单词“ accumulate”,“ price”,“ below”的组合。

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式,请参见https://regex101.com/

const regex = /accumulate.*price.*below/gm;
const str = `we could accumulate it at the price below 4000

we could do it at the price below 4000'`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}