Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this JavaScript Regex match an underscore?

I am trying to use following JavaScript RE to match the string where allowed characters are uppercase or lowercase letters, digits, hypens (-), and periods (.). The underscore "_" is not allowed:

pattern = /^([a-zA-z0-9\-\.]+)$/

But when I run the test in the Chrome console: pattern.test("_linux");

The result is true, but should be false according to our rules. What's the reason?

like image 531
flashstar Avatar asked Jan 06 '23 13:01

flashstar


1 Answers

In your regex, you have written A-z (with a lowercase z at the end). In the JavaScript regex engine, this translates to character codes 65 to 122 rather than the desired 65 to 90. And the underscore character is within this range (char code 95); see an ASCII chart. Change it to a capital Z, making your regex:

^([a-zA-Z0-9\-\.]+)$
like image 99
rvighne Avatar answered Jan 15 '23 08:01

rvighne