Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++;
like image 846
Aajiz Avatar asked Nov 29 '22 15:11

Aajiz


2 Answers

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.

like image 61
Wouter J Avatar answered Dec 11 '22 16:12

Wouter J


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).

like image 22
Edwin Avatar answered Dec 11 '22 15:12

Edwin