javascript - 使用 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"];
解决方案
您可以通过加入单词数组来构造一个正则表达式|
,然后用单词边界将其包围\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]);
推荐阅读
- ruby - gem 忘记安装的包
- mongodb - Mongodb分组并返回所有结果
- android - 如何在输入文本时在文本输入字段中应用自定义字体?
- android - 监控 android 应用程序以进行用户调试
- android - Android资源链接在绑定适配器数据绑定中失败
- python - 如何将子文件夹中的文本与 Python 结合起来
- javascript - 在 Flutter Web 中扫描条形码的可能性
- javascript - 如何使用重定向模式(无弹出)从 Google Signin 获取个人资料信息?
- python - 在 pycharm 中需要有关 pyinstaller 的帮助
- html - 垂直对齐 CSS 中相邻的项目