Reputation: 2289
I want to validate the string, which should not contain any special characters except underscore(_). For that i have written below code but i was not able to get it through.
var string = 'pro$12';
var result = /[a-zA-Z0-9_]*/.test(string);
In the above the given string is not valid but i got the result as a true. Can any body tell what i am doing wrong here?
Upvotes: 1
Views: 54
Reputation: 239443
It returns true
because, it is able to match pro
. You can see the actual matched string, with the match
function, like this.
console.log(string.match(/[a-zA-Z0-9_]*/));
# [ 'pro', index: 0, input: 'pro$12' ]
Even when it doesn't match anything, for example, your input is '$12', then also it will return true
. Because, *
matches 0 or more characters. So, it matches zero characters before $
in $12
. (Thanks @Jack for pointing out)
So, what you actually need is
console.log(/^[a-zA-Z0-9_]*$/.test(string));
# false
^
means beginning of the string and $
means ending of the string. Basically you are telling the RegEx engine that, match a string which has only the characters from the character class, from the beginning and ending of the string.
Note: Instead of using the explicit character class, [a-zA-Z0-9_]
, you can simply use \w
. It is exactly the same as the character class you mentioned.
Quoting from MDN Docs for RegExp,
\w
Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to
[A-Za-z0-9_]
.For example,
/\w/
matches'a'
in"apple,"
'5'
in"$5.28,"
and'3'
in"3D."
So, your RegEx can be shortened like this
console.log(/^\w*$/.test(string));
Upvotes: 1