'Javascript match function for special characters
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++;
Solution 1:[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:[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:[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:[4]
Just do what you did above, but create a group for !@#$%^&*() etc. Just be sure to escape characters that have meaning in regex, like ^ and ( etc....
EDIT -- I just found this which lists characters that have meaning in regex.
Solution 5:[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]/.
Solution 6:[6]
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 7:[7]
/[^a-zA-Z0-9 ]+/ This will accept only special characters and will not accept a to z & A to Z 0 to 9 digits
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wouter J |
| Solution 2 | |
| Solution 3 | Flambino |
| Solution 4 | hvgotcodes |
| Solution 5 | mgibsonbr |
| Solution 6 | karora |
| Solution 7 | QUTBUDDIN KHAN |
