首页 > 解决方案 > 使用 JavaScript 检查变量中是否存在多个单词

问题描述

该代码在一个句子中存在一个单词并且它工作正常。

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');
}

这是我的问题:我需要检查一个句子中是否存在多个单词(例如:食物、豆类、车前草等),然后还提醒匹配的单词。就像是//alert(' The matched word is' +matched_word);

我想我必须按照以下方式在数组中传递搜索到的单词:

var  words_checked = ["food", "beans", "plantain"];

标签: javascript

解决方案


您可以通过加入单词数组来构造一个正则表达式|,然后用单词边界将其包围\b

var words_checked = ['foo', 'bar', 'baz']
const pattern = new RegExp(String.raw`\b(?:${words_checked.join('|')})\b`);
var str = 'fooNotAStandaloneWord baz something';

console.log('Match:', str.match(pattern)[0]);


推荐阅读