Jeroen Steen Jeroen Steen - 4 months ago 11
Javascript Question

Match special characters regex in Javascript (Random place)

I'm trying to make a regex to match atleast two special characters,
for a password strength checker. I now have this in Javascript:

if (password.match(/([^A-Za-z0-9]{2,})/)) {
//Add strength
}


But this checks that atleast two special characters that needs to be after each other. How can I make it, so that it will also check if it's not after each other?

Example:

_aaa!* //Match
a!a_a* //Also match

Answer

One way to do it:

var password = 'a!a_a*';
var matches = password.match(/([^A-Za-z0-9])/g);

if (matches && matches.length >= 2) {
  console.log('Good');
} else {
  console.log('Bad');
}

console.log(matches);

Comments