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.
Asked
Active
Viewed 4.4k times
22

CBuzatu
- 745
- 5
- 16
- 29
4 Answers
35
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}$/;

Joel Etherton
- 37,325
- 10
- 89
- 104
-
The second regex isn't quite right. `|` has lower precendence than `^` and `$`. You can also simplify by just making the `[1-9]` optional. `/^[1-9]?\d{1}$/` – Matt Ball May 27 '12 at 02:51
-
Just realized you can do even better - `\d{1}` is redundant, and equivalent to `\d`. – Matt Ball May 27 '12 at 02:58
-
7I'd go with `/^[1-9]?\d$/` No need for alternation, just make the leading digit optional. – Mark Reed May 27 '12 at 03:02
-
@MarkReed, your decision is cool but one digit zero is valid for your Regex – iamarsey Oct 28 '15 at 09:43
-
Yes. 0 by itself is valid. That's intentional. – Mark Reed Oct 28 '15 at 12:15
2
Try this.
/^[0-9]|[0-9][0-9]$/
This should do the job. Using an Or operator does it.

Vishak Kavalur
- 449
- 1
- 5
- 12