我有一个超过2K的JSON数组
const Keyword = [
{
"key": "hello",
"word": "hi. how may i help you?"
},
{
"key": "how are you?",
"word": "I'm good, what about you? "
}
]
我的话
hello , are you available right now?
现在我需要用JSON键hello与我的单词if match然后返回结果true或false进行匹配和查找,
我尝试了下面的代码
const text = "hello , are you available right now?"
if (
Keyword.find((arr) => arr.key.toLowerCase() === text.toLowerCase()) ===
undefined
) {
return false;
} else {
return true;
}
现在的问题是它找到确切的单词,但我需要一个解决办法来找到与匹配
谢谢
可以对字符串使用includes方法检查它是否包含子字符串
null
const Keyword = [
{
"key": "hello",
"word": "hi. how may i help you?"
},
{
"key": "how are you?",
"word": "I'm good, what about you? "
}
]
const text = "hello , are you available right now?"
const found = Keyword.find(item => text.toLowerCase().includes(item.key.toLowerCase()))
console.log(found)
使用regexp查找关键字的简单函数:
null
const Keyword = [{
"key": "hello",
"word": "hi. how may i help you?"
}, {
"key": "how are you?",
"word": "I'm good, what about you? "
}]
const findKeyword = (text) =>
Keyword.find(r => new RegExp(r.key, 'i').test(text))
console.log(
findKeyword("Hello, are you available right now?")
)