I have the below code. It works only when I have 2 digits. If I have 1 digit doesn't work. I want to work in both cases: one or two digit.var numberRegex = /^[1-9][0-9]$/;
I've tried something like this but unfortunately doesn't work:var numberRegex = /^[1-9]?[1-9][0-9]$/;
Thanks for support.
Occurrence Indicators (or Repetition Operators): +: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.
To match a two digit number / \d{2} / is used where {} is a quantifier and 2 means match two times or simply a two digit number. Similarly / \d{3} / is used to match a three digit number and so on.
The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.
Try this one out:
/^\d{1,2}$/;
Reading what you have it looks like you don't want to accept numbers like 01
.
/^\d{1}|[1-9]\d{1}$/;
Try this.
/^[0-9]|[0-9][0-9]$/
This should do the job. Using an Or operator does it.
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