javascript - match string against the array of regular expressions

前端 未结 8 1567
予麋鹿
予麋鹿 2020-12-02 22:23

Is there a way in JavaScript to get Boolean value for a match of the string against the array of regular expressions?

The example would be (where the \'if\' statemen

8条回答
  •  醉话见心
    2020-12-02 22:51

    You can join all regular expressions into single one. This way the string is scanned only once. Even with a sligthly more complex regular expression.

    var thisExpressions = [ /something/, /something_else/, /and_something_else/];
    var thisString = 'else';
    
    
    function matchInArray(str, expr) {
        var fullExpr = new RegExp(expr
            .map(x=>x.source) // Just if you need to provide RegExp instances instead of strings or ...
            // .map(x=>x.substring(1, x.length -2)  // ...if you need to provide strings enclosed by "/" like in original question.
            .join("|")
        )
        return str.match(fullExpr);
    
    };
    
    
    if (matchInArray(thisString, thisExpressions)) {
        console.log ("Match!!");
    } 
    

    In fact, even with this approach, if you need check the same expression set against multiple strings, this is a few suboptimal because you are building (and compiling) the same regular expression each time the function is called.

    Better approach would be to use a function builder like this:

    var thisExpressions = [ /something/, /something_else/, /and_something_else/];
    var thisString = 'else';
    
    function matchInArray_builder(expr) {
        var fullExpr = new RegExp(expr
            .map(x=>x.source) // Just if you need to provide RegExp instances instead of strings or ...
            // .map(x=>x.substring(1, x.length -2)  // ...if you need to provide strings enclosed by "/" like in original question.
            .join("|")
        )   
    
        return function (str) {
            return str.match(fullExpr);
    
        };
    };  
    
    var matchInArray = matchInArray_builder(thisExpressions);
    
    if (matchInArray(thisString)) {
        console.log ("Match!!");
    } 
    

提交回复
热议问题