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"];
3
  • "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. Commented Oct 29, 2020 at 16:35
  • \b(food|beans|plantain|yam)\b Commented Oct 29, 2020 at 16:38
  • Does this answer your question? Check if string contains any of array of strings without regExp Commented Oct 29, 2020 at 16:42

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

1 Comment

Would you edit your answer to explain how it answers the question? Future readers may find that useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.