首页 > 解决方案 > 使用数组在字符串中查找特定单词 (JavaScript)

问题描述

我有一个名为“你好”的数组,其中包含表达式

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 很陌生

标签: javascriptarraysstringincludematch

解决方案


使用 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?");
}

一些文件


推荐阅读