javascript - 使用数组在字符串中查找特定单词 (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 很陌生
解决方案
使用 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?");
}
一些文件
推荐阅读
- android - 应用无法连接到 Firebase 实时数据库
- mongodb - 连接远程机器上运行的mongodb
- elasticsearch - 弹性搜索:hour_minute_second 映射返回空数据
- java - 单元测试 JMS 有效负载
- ios - 使用文本层导出视频时 AVFoundation 崩溃
- ios - 自定义视图在 Xcode 11.4 上不起作用 Testfligt
- c++ - 如何检测调用结果是否有效
- javascript - 如何让我的垫片在固定头中工作?
- ansible - 解包 ansible 结果变量
- oop - Groovy:Class.forName().newInstance() 错误