Search code examples
javascriptarraysexpression

javascript - match string against the array of regular expressions


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' statement is representing what I'm trying to achieve):

var thisExpressions = [ '/something/', '/something_else/', '/and_something_else/'];
var thisString = 'else';

if (matchInArray(thisString, thisExpressions)) {

} 

Solution

  • 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)​