Radex Radex -4 years ago 83
Javascript Question

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

I have the following regular expression

and I need to return false when the string contains only characters from
lower and uppercase, numbers, 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);

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:

 ^             ^^

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download