In JavaScript, how can I use regex to match unless words are in a list of excluded words?

后端 未结 4 1641
挽巷
挽巷 2020-12-10 04:14

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

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 04:38

    Don't Hard-Code Your Regular Expressions

    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
    

提交回复
热议问题