Radex Radex -4 years ago 83
Javascript Question

Regular expression /[a-zA-Z0-9_-]/ return true when passing `!!!`

I have the following regular expression

/[a-zA-Z0-9_-]/
and I need to return false when the string contains only characters from
a
to
z
lower and uppercase, numbers, and
_
and
-
.


  • What is wrong with my code?

  • Could you please provide me a brief explanation and a sample of code on how to fix it?





//var str = 'EKyirtVHsK0'; ok
var str = '!%!irtVHsK0'; // should return false
var result = /[a-zA-Z0-9_-]/.test(str);
alert(result);




Answer Source

Your string contains symbols that are matched with your regex that finds partial matches. In fact, if you use str.match(/[a-zA-Z0-9_-]/), you will see you matched i.

Add anchors and a quantifier:

/^[a-zA-Z0-9_-]*$/
 ^             ^^

Or, if 1+ chars are required in the input:

/^[a-zA-Z0-9_-]+$/
               ^
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download