I am getting inconsistent results when using JavaScript’s RegEx to validate numbers with a decimal place. The goal is to have any combination of digits followed by a decimal point and two more digits. It works fine except with numbers in the thousands (no separators).
This is the expression I’m using:
^[0-9]+(\.[0-9][0-9])$
Valid numbers:
10.99
0.75
999.99
5000.99
...etc
Invalid Numbers:
1000
.75
0
...etc
The problem is that it matches whole numbers in the thousands. This is for an internal application so I’m not concerned about using additional separators. I’ve tested the expression out with tools like http://regexpal.com/ which gives me the results that I need, so it appears that there is something in the JS causing the issue.
You can duplicate the problem here:
http://jsfiddle.net/hcAcQ/
You need to escape the backslash before the
., I believe:The reason that a 4 digit (or greater) number will work is because the single backslash isn’t actually escaping that
.to be a period character, thus causing it to act as the wildcard “match any character” dot.When you have 3 or fewer digits this fails because there aren’t enough characters for every match in the regex, but the with 4 digits it will work (one digit for the first character class, one for the
., and one each for the other two character classes.Escaping the
\will cause the.to actually be interpreted as a literal.character, as you probably intended. You could also instead define your variable as a regex literal (MDN example; near the top) so that you don’t have to deal with escaping\characters within the string: