Javascript match function for special characters

*爱你&永不变心* 提交于 2019-12-10 20:57:25

问题


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++;

回答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.




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




回答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.




回答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.




回答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]/.




回答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.
}


来源:https://stackoverflow.com/questions/9230595/javascript-match-function-for-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!