Q:

How to match single words AND combinations of words using regex?

I'm trying to match a users text input against a set of predefined keywords and phrases.
Example:
var keywordRegEx = /\b(nutrition|protein|muscle|muscle growth|muscle repair|muscle food|foods)\b/ig;

var user_input = "What are the best foods for muscle growth and muscle repair";
var matches = user_input.match(keywordRegEx);

console.log(matches); 
//["foods", "muscle", "muscle"]

But what I want to see in the console is:
//["foods", "muscle", "muscle growth", "muscle repair"]

Is there any way to match against single whole words AND combinations including those whole words using regex?
*Note that if I remove "muscle" from the the list of predefined keywords and phrases I get the following:
var keywordRegEx = /\b(nutrition|protein|muscle growth|muscle repair|muscle food|foods)\b/ig;

var user_input = "What are the best foods for muscle growth and muscle repair";
var matches = user_input.match(keywordRegEx);

console.log(matches);
//["foods", "muscle growth", "muscle repair"]

But I need to be able to match single words by themselves..
I'm fairly lost when it comes to regex so any help here would be greatly appreciated.
Thanks in advance

A:

To catch single words and their combinations you can use two RegExps and combine them into single array. Such solution is easier to read and probably faster than a single RegExp:

var keywordRegEx = /nutrition|protein|foods|muscle/g;
var keywordPairsRegEx = /muscle growth|muscle repair|muscle food/g;

var user_input = "What are the best foods for muscle growth and muscle repair";
var matches = user_input.match(keywordRegEx) //first regex
            .concat(user_input.match(keywordPairsRegEx)) //second regex
            .filter(( item, index, inputArray ) => { //remove duplicates
              return inputArray.indexOf(item) == index;
            });

console.log(matches);

