Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use /^d{1,2}$/ when a JavaScript string must contain exactly one or two digits. The anchors require the entire string to match, d matches a digit in the SitePoint discussion’s notation, and {1,2} sets a minimum of one and maximum of two repetitions.

The pattern

/^d{1,2}$/

This matches numeric-looking strings such as "3", "7", "12", and "45". It does not parse a JavaScript number; it validates the text representation.

How each part works

  • ^ anchors the match at the beginning of the string.
  • d represents one digit in the forum’s expression.
  • {1,2} requires at least one and at most two repetitions. The comma separates the lower and upper bounds.
  • $ anchors the match at the end of the string.

Because both anchors are present, values with extra characters or more than two digits fail the whole-string test.

Why {1|2} is not the right quantifier

/^d{1|2}$/ does not express “one or two repetitions.” Quantifier bounds use a comma: {minimum,maximum}. Alternation uses a vertical bar outside the quantifier, as in foo|bar.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Example in JavaScript

const oneOrTwoDigits = /^d{1,2}$/;

oneOrTwoDigits.test("3");   // true
oneOrTwoDigits.test("45");  // true
oneOrTwoDigits.test("123"); // false
oneOrTwoDigits.test("a7");  // false
oneOrTwoDigits.test(7);      // false: test the string form instead

If your input is a number rather than text, convert it deliberately with String(value) before testing, while remembering that numeric conversion has already discarded formatting such as leading zeroes.

Allowing exactly five or nine digits

A range such as {5,9} would allow every length from five through nine. To allow only five or nine digits, use one of these forms:

/^d{5}$|^d{9}$/

/^d{5}(d{4})?$/

The first uses alternation between two complete anchored patterns. The second requires five digits and makes four additional digits optional, so the total length is exactly five or exactly nine.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Important scope

This pattern checks digit count, not numeric range. It accepts strings such as "00" and "09". If the value must be between specific numbers, validate the format first and then apply a numeric range check.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.