How do I use regex to match any word (\\w) except a list of certain words? For example:
I want to match the words use and utilize and any w
Rather than trying to put all your search and exclusion terms into a single, hard-coded regular expression, it's often more maintainable (and certainly more readable) to use short-circuit evaluation to select strings that match desirable terms, and then reject strings that contain undesirable terms.
You can then encapsulate this testing into a function that returns a Boolean value based on the run-time values of your arrays. For example:
'use strict';
// Join arrays of terms with the alternation operator.
var searchTerms = new RegExp(['use', 'utilize'].join('|'));
var excludedTerms = new RegExp(['fish', 'something'].join('|'));
// Return true if a string contains only valid search terms without any
// excluded terms.
var isValidStr = function (str) {
return (searchTerms.test(str) && !excludedTerms.test(str));
};
isValidStr('use fish'); // false
isValidStr('utilize hammer'); // true