简体   繁体   中英

Javascript regexp character matching

I'm looking into using a jQuery password strength indicator and have found one that looks suitable.

It increases the password strength score if special characters are detected:

if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)){ score += 5 ;}

However I'd like to be able to specify additional special characters and because these lists of special characters are used in several places, I'd like to only specify the list once:

list = array(!,@,#,$,%,^,&,*,?,_,~,[,],{,},(,));
if (password.match(/(.*[list].*[list])/)){ score += 5 ;}

Is this possible?

You can use strings:

var special = "!@#$%^&*?_~[]{}()".split('').join('\\');
if (password.match(new RegExp("(.*[" + special + "].*[" + special + "])")))...

(The join-with-backslashes escapes the special characters so they are treated literally by the regex engine.)

Yes, if you use the RegExp() constructor , you can pass in a string as regexp.

var list = ['\\!', '\\@', '\\#', '\\%'];
var reg = new RegExp('(.*['+ list.join(',') + '].*['+ list.join(',') +'])');
if (reg.test("MySuperPassword!#_123")) {
    score += 5;
}

You do not need to separate chars by , in regex:

var list = "[\\!@#\\$%\\^&\\*\\?_~]";
var your_regex = new RegExp(".*" + list + ".*" + list);
if (your_regex.test(password)){
  score += 5;
}

Why would you need a regex?

var list  = ['!','@','#','$','%','^','&','*','?','_','~','[',']','{','}','(',')'],
    score = 0;

for (var i=list.length;i--;) {
    if ( password.indexOf(list[i]) ) score++;
}

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM