【问题标题】:How to search through a string with an array of strings (js)?如何使用字符串数组(js)搜索字符串?
【发布时间】:2022-01-23 19:36:59
【问题描述】:

我想要做的是下面的例子(除了它不起作用的部分): 我想过滤一个字符串(消息),它检查字符串数组(异常),结果为真(对于数组中的任何字符串)或假(如果数组中没有字符串) . 我不知道如何进行这项工作,因为我发现的大多数信息似乎只做相反的事情(使用单个字符串搜索字符串数组)。

任何帮助将不胜感激!

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!");                                         
}

【问题讨论】:

    标签: javascript arrays string


    【解决方案1】:

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

    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

    【讨论】:

    • 也许你的解决方案比我的“更好”;可能会向它添加一些 toLowerCase() 以便它检查大小写差异。只是添加一个注释:我认为 str.includes() 会检查整个单词是否完全匹配,但是否包含在其中。 'apple' 上的 "applejuice" 将是真的。
    • 为了准确检查,正则表达式会更好。
    【解决方案2】:
        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");
            })
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-15
      • 2011-07-22
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      相关资源
      最近更新 更多