I’m attempting to write a piece of regex code that verifies an age that has 1,2, or 3 digits for a simple form. If it has 3 digits, the leading digit must be a 1, and the leading digit is never 0.
What I have so far:
/^1[0-9][0-9]$|^[0-9][0-9]$|^[0-9]$/
An example of this odd behavior:
> myRe = /^1[0-9][0-9]$|^[0-9][0-9]$/;
> myRe.exec(023);
["19"]
> myRe.exec(052);
["42"]
023is a number, and regular expressions don’t work on numbers. So JavaScript converts the number into a string first. And because of the zero, it is an octal number; so 023 is actually2 * 8 + 3, and not2 * 10 + 3.You want to do
myRe.exec("023")instead. Also, you might want to modify your regex so that the first digit in the double-digit branch and the single digit in the last branch read[1-9], and not[0-9].