0

The code the presence of a single word in a sentence and it's working fine.

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

Here is my issue: I need to check presence of multiple words in a sentence (eg: food,beans,plantains etc) and then also alert the matched word. something like //alert(' The matched word is' +matched_word);

I guess I have to passed the searched words in an array as per below:

var  words_checked = ["food", "beans", "plantain"];
halfer
  • 19,824
  • 17
  • 99
  • 186
Nancy Moore
  • 2,322
  • 2
  • 21
  • 38
  • _"I guess I have to passed the searched words in an array "_ - yes, that will work. Put all the works in an array and then iterate over the array and use `str.includes(currentWord)` to check the existence of current word in the string. – Yousaf Oct 29 '20 at 16:35
  • `\b(food|beans|plantain|yam)\b` – Randy Casburn Oct 29 '20 at 16:38
  • Does this answer your question? [Check if string contains any of array of strings without regExp](https://stackoverflow.com/questions/46925420/check-if-string-contains-any-of-array-of-strings-without-regexp) – Aib Syed Oct 29 '20 at 16:42

3 Answers3

1

You can construct a regular expression by joining the array of words by |, then surround it with word boundaries \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]);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0
var text = "I am happy, We all are happy";
var count = countOccurences(text, "happy");

// count will return 2 //I am passing the whole line and also the word for which i want to find the number of occurences // The code splits the string and find the length of the word

function countOccurences(string, word){
      string.split(word).length - 1;
}
Man87
  • 131
  • 6
  • Would you edit your answer to explain how it answers the question? Future readers may find that useful. – halfer Oct 30 '20 at 08:17
0

Here's a way to solve this. Simply loop through the list of words to check, build the regex as you go and check to see if there is a match. You can read up on how to build Regexp objects 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');
    }
}
nicks6853
  • 40
  • 8