【发布时间】:2023-04-02 11:52:01
【问题描述】:
代码中存在一个句子中的单个单词,它工作正常。
var str ="My best food is beans and plantain. Yam is also good but I prefer yam porrage"
if(str.match(/(^|\W)food($|\W)/)) {
alert('Word Match');
//alert(' The matched word is' +matched_word);
}else {
alert('Word not found');
}
这是我的问题:我需要检查一个句子中是否存在多个单词(例如:food,beans,plantains 等),然后还提醒匹配的单词。
类似//alert(' The matched word is' +matched_word);
我想我必须按照以下方式将搜索到的单词传递给数组:
var words_checked = ["food", "beans", "plantain"];
【问题讨论】:
-
“我想我必须在数组中传递搜索到的单词” - 是的,这会起作用。将所有作品放在一个数组中,然后遍历数组并使用
str.includes(currentWord)检查字符串中当前单词的存在。 -
\b(food|beans|plantain|yam)\b
标签: javascript