javascript - match string against the array of regular expressions

前端 未结 8 1572
予麋鹿
予麋鹿 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:47

    http://jsfiddle.net/9nyhh/1/

    var thisExpressions = [/something/, /something_else/, /and_something_else/];
    var thisExpressions2 = [/else/, /something_else/, /and_something_else/];
    var thisString = 'else';
    
    function matchInArray(string, expressions) {
    
        var len = expressions.length,
            i = 0;
    
        for (; i < len; i++) {
            if (string.match(expressions[i])) {
                return true;
            }
        }
    
        return false;
    
    };
    
    setTimeout(function() {
        console.log(matchInArray(thisString, thisExpressions));
        console.log(matchInArray(thisString, thisExpressions2));
    }, 200)​
    

提交回复
热议问题