提问者:小点点

如何使用字符串数组(js)搜索字符串?


我试图做的是下面的例子(除了不起作用的部分):我想过滤字符串(消息),它检查字符串数组(异常),结果为true(数组中的任何字符串)或false(如果数组中没有任何字符串)。我不知道该怎么做,因为我找到的大多数信息似乎都是相反的(用单个字符串搜索字符串数组)。

任何帮助将不胜感激!

var Message = "i bought a pear";
const Trigger = "bought";
const Exception = ["apple", "pear", "banana"]

if ((Message.includes(Trigger)) && (!Message.includes(Exception))) {
    console.log("Trigger hit!");                                         
}

共2个答案

匿名用户

您需要迭代异常数组并检查消息。

const
    message = "i bought a pear",
    trigger = "bought",
    exception = ["apple", "pear", "banana"];

if (message.includes(trigger) && !exception.some(e => message.includes(e))) {
    console.log("Trigger hit!");                                         
}

console.log(exception.some(e => message.includes(e))); // true

匿名用户

    let message = "i bought a pear";
    const trigger = "bought";
    const exceptions = ["apple", "pear", "banana"];

    let newMessageArr = message.split(' ');
    exceptions.forEach((exception) => {
        console.log(exception);
        newMessageArr.forEach(word => {
            if( word === exception )
                console.log("true");
        })
    })