Javascript match function for special characters
Solution 1
If you mean !@#$% and ë as special character you can use:
/[^a-zA-Z ]+/
The ^
means if it is not something like a-z or A-Z or a space.
And if you mean only things like !@$&$ use:
/\W+/
\w
matches word characters, \W
matching not word characters.
Solution 2
You'll have to whitelist them individually, like so:
if(password.match(/[`~!@#\$%\^&\*\(\)\-=_+\\\[\]{}/\?,\.\<\> ...
and so on. Note that you'll have to escape regex control characters with a \
.
While less elegant than /[^A-Za-z0-9]+/
, this will avoid internationalization issues (e.g., will not automatically whitelist Far Eastern Language characters such as Chinese or Japanese).
Solution 3
you can always negate the character class:
if(password.match(/[^a-z\d]+/i)) {
// password contains characters that are *not*
// a-z, A-Z or 0-9
}
However, I'd suggest using a ready-made script. With the code above, you could just type a bunch of spaces, and get a better score.
Solution 4
As it look from your regex, you are calling everything except for alphanumeric a special character. If that is the case, simply do.
if(password.match(/[\W]/)) {
// Contains special character.
}
Anyhow how why don't you combine those three regex into one.
if(password.match(/[\w]+/gi)) {
// Do your stuff.
}
Solution 5
if(password.match(/[^\w\s]/)) score++;
This will match anything that is not alphanumeric or blank space. If whitespaces should match too, just use /[^\w]/
.
Aajiz
Updated on February 11, 2020Comments
-
Aajiz about 4 years
I am working on this code and using "match" function to detect strength of password. how can I detect if string has special characters in it?
if(password.match(/[a-z]+/)) score++; if(password.match(/[A-Z]+/)) score++; if(password.match(/[0-9]+/)) score++;