【问题标题】:Checking the presence of multiple words in a variable using JavaScript使用 JavaScript 检查变量中是否存在多个单词
【发布时间】: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


【解决方案1】:

你可以通过|连接单词数组来构造一个正则表达式,然后用单词边界\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]);

【讨论】:

    【解决方案2】:

    这是解决此问题的一种方法。只需循环检查要检查的单词列表,构建正则表达式并检查是否有匹配项。您可以阅读如何构建 Regexp 对象here

    var str ="My best food is beans and plantain. Yam is also good but I prefer 
              yam porrage"
    var words = [
        "food",
        "beans",
        "plantain",
        "potato"
    ]
    
    for (let word of words) {
        let regex = new RegExp(`(^|\\W)${word}($|\\W)`)
    
        if (str.match(regex)) {
            console.log(`The matched word is ${word}`);
        } else {
            console.log('Word not found');
        }
    }
    

    【讨论】:

      【解决方案3】:
      var text = "I am happy, We all are happy";
      var count = countOccurences(text, "happy");
      

      // 计数将返回 2 //我正在传递整行以及我想要查找出现次数的单词 // 代码拆分字符串,求单词的长度

      function countOccurences(string, word){
            string.split(word).length - 1;
      }
      

      【讨论】:

      • 你会编辑你的答案来解释它是如何回答这个问题的吗?未来的读者可能会发现这很有用。
      猜你喜欢
      • 1970-01-01
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      • 2011-08-18
      • 2014-01-20
      相关资源
      最近更新 更多