makerofthings7
makerofthings7

Reputation: 61463

How do I match a symbol in Javascript?

I'm working on a password validation screen and the requirement is to have at least one symbol such as the ones listed below.

How should I escape them so it works correctly under Javascript?

//validate symbol
if (pswd.match(/`~!@#$%^&*()_+=-\][{}\;':"<>?,/./)) {
    $('#symbol').removeClass('invalid').addClass('valid');
} else {
    $('#symbol').removeClass('valid').addClass('invalid');
}

Upvotes: 0

Views: 142

Answers (3)

nhahtdh
nhahtdh

Reputation: 56809

I'm not sure the characters that you want to match, since the original string is quite messy. Check whether this is all the characters you want:

"we?dn^~!@#$%^&*()_+-={dsfs}sf[]\\|:\";',./?><".match(/[`~!@#$%^&*()_+=\]\[{};':"<>?,\/.-]/g)
>> ["?", "^", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+", "-", "=", "{", "}", "[", "]", ":", """, ";", "'", ",", ".", "/", "?", ">", "<"]

For the sake of clarity, this is the regex:

/[`~!@#$%^&*()_+=\]\[{};':"<>?,\/.-]/

EDIT

If you want to include \ and | use this regex:

/[\\`~!@#$%^&*()_+=\]\[{};':"<>?,\/.|-]/

Upvotes: 0

kennebec
kennebec

Reputation: 104780

The slashes and right-square-bracket are the only ones that need to be escaped in a character group-as long as the hyphen is not between two characters.

if(/[/`~!@#$%^&*()_+=[{};':"<>?,.\/\]-]/.test(pswd) ){

Upvotes: 1

dinox0r
dinox0r

Reputation: 16039

Use this instead:

if (pswd.match(/[^A-Za-z0-9]+/)) {

It matches any text that contains at least one character that is not in the list [A-Za-z0-9]

Upvotes: 2

Related Questions