【问题标题】:Use an array to find a specific word in a string (JavaScript) [duplicate]使用数组在字符串中查找特定单词(JavaScript)[重复]
【发布时间】:2021-12-11 18:07:37
【问题描述】:

我有一个名为 'hello' 的数组,其中包含表达式

var hello = ['hi', 'hello', 'yo', 'hey', 'howdy'];
        

我从用户那里得到一个存储在 'usertext' 中的字符串。

我想检查 'usertext' 是否包含存储在 'hello' 中的表达式之一并返回 true/false, ' usertext' 可以包含一个完整的句子。

到目前为止我尝试过

if (usertext.includes(hello)) {
    var garfieldtext = "Hello. I'm Garfield, what's your name?";
}

很抱歉,如果已经有人问过,我没有找到(或理解)解决方案。

我对 JS 很陌生

【问题讨论】:

    标签: javascript arrays string include match


    【解决方案1】:

    利用 JavaScript 的 some 方法。如果满足任何条件,则返回true

    const hello = ['hi', 'hello', 'yo', 'hey', 'howdy'];
    const userText = "some text in here hello";
    
    const helloExist = hello.some(item => userText.toLowerCase().includes(item));
    
    if (helloExist) {
        console.log("Hello. I'm Garfield, what's your name?");
    }

    some 的文档

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      相关资源
      最近更新 更多