Creating Array of Regular Expressions Javascript Creating Array of Regular Expressions Javascript arrays arrays

Creating Array of Regular Expressions Javascript


You don't need the loop to test every word as you can put them all into one regular expression (separated by the | character) and let the regex engine look for any of them all at once. You could do that like this:

function unacceptable(pwd){    var unforgivable = [        "password",        "12345678",        "8675309",        "[a-z]{8,}",        "qwerty",        "asdfg",        "qazwsx",        "zxcvb",        "letmein",        "trustno1",        "omnicloud",        "monkey"    ];    var re = new RegExp(unforgivable.join("|"), "i");    return re.test(pwd);}

Working demo here: http://jsfiddle.net/jfriend00/cyVbC/

P.S. You don't have to put all the words into an array. You could just predeclare the entire regex, but I thought putting them in the array like this made for more readable code that was easier to maintain.

It could also be this:

var unforgivable = /password|12345678|8675309|[a-z]{8,}|qwerty|asdfg|qazwsx|zxcvb|letmein|trustno1|omnicloud|monkey/i;function unacceptable(pwd){    return unforgivable.test(pwd);}


I like using Array.some, which will stop iterating through the array as soon as one return value is true:

function unacceptable(pwd){    return [        /password/gi,        /12345678/g,        /8675309/g,        /[a-z]{8,}/gi,        /qwerty/gi,        /asdfg/gi,        /qazwsx/gi,        /zxcvb/gi,        /letmein/gi,        /trustno1/gi,        /omnicloud/gi,        /monkey/gi    ].some(function(regexp){        return regexp.test(pwd);    });}


You have a trailing comma. You can't use a trailing comma in javascript.

var unforgivable = new Array(    /password/gi, /*g matches any occurance of sequence, i checks case insensitive*/    /12345678/g,    /8675309/g,    /[a-z]{8,}/gi,    /qwerty/gi,    /asdfg/gi,    /qazwsx/gi,    /zxcvb/gi,    /letmein/gi,    /trustno1/gi,    /omnicloud/gi,    /monkey/gi)