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?
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\-\.]+)$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With