Nancy Moore
Nancy Moore

Reputation: 2470

Checking the presence of multiple words in a variable using JavaScript

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"];

Upvotes: 0

Views: 906

Answers (3)

Man87
Man87

Reputation: 131

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

Upvotes: 0

nicks6853
nicks6853

Reputation: 40

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

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370809

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]);

Upvotes: 1

Related Questions