JavaScript RegExp {X,Y} Quantifier

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Bounded range

What You’ll Learn

The {X,Y} quantifier matches the previous token between X and Y times, inclusive. Use \d{2,4} for two-to-four digits, {8,64} for password length limits, and remember that ? is shorthand for {0,1}.

01

{n,m}

Min to max

02

\d{2,4}

2–4 digits

03

{0,1}

Same as ?

04

{n,n}

Same as {n}

05

Greedy

Max in range

06

{n,m}?

Lazy mode

Introduction

Exact counts ({4}) and open-ended minimums ({3,}) cover many cases. But real-world rules often need both a floor and a ceiling: usernames between 3 and 16 characters, area codes with two to four digits, or hex colors with three to six hex digits. The {X,Y} quantifier sets that bounded range.

Write {n,m} where n is the minimum and m is the maximum number of repetitions. The engine matches at least n and at most m of the preceding token. Combined with anchors, this is the standard way to enforce field length limits in regex validation.

Understanding the {X,Y} Range Quantifier

Place {n,m} immediately after a token. The engine tries to match that token at least n times and no more than m times. By default it is greedy—it prefers the maximum allowed count when possible.

JavaScript
/^\d{2,4}$/.test("12");     // true

/^\d{2,4}$/.test("1234");   // true

/^\d{2,4}$/.test("12345");  // false — exceeds max

/^\d{2,4}$/.test("1");      // false — below min



"12345".match(/\d{2,4}/);   // ["1234"] — greedy max in range

Without anchors, {n,m} finds a qualifying substring anywhere in the input. With ^ and $, the entire value must fall within the range.

💡
Beginner Tip

In tutorials we write {X,Y} as placeholders. In real patterns use numbers: {2,4}, {8,64}. The minimum must not exceed the maximum—{4,2} is invalid and throws a SyntaxError.

How to Use the {X,Y} Quantifier

Attach {n,m} after a character class, metacharacter, dot, or grouped expression:

JavaScript
/\d{2,4}/;                    // 2 to 4 digits

/^.{8,64}$/;                  // 8–64 chars (password)

/(ha){2,3}/;                  // 2–3 ha units

/colou?r/;                    // same as /colou{0,1}r/

/#[0-9a-fA-F]{3,6}/;          // hex color length

Use test() for validation, match() to extract the bounded run, and {n,m}? when you need the shortest match that still satisfies the range.

📝 Syntax

JavaScript
token{n,m}         // between n and m repetitions (inclusive)

{0,1}              // zero or one (same as ?)

{n,n}              // exactly n (same as {n})

{n,}               // at least n (no max)

\d{2,4}            // 2–4 digits

.{3,16}            // 3–16 any characters

Common patterns

  • /^\d{2,4}$/ — whole field is two to four digits.
  • /^[\w]{3,16}$/ — username between 3 and 16 word characters.
  • /#[0-9a-fA-F]{3,6}/ — CSS hex color with 3–6 hex digits.
  • /colou{0,1}r/ — optional u for colour/color (same as colou?r).
  • /(ab){2,4}/ — two to four repetitions of the ab group.

⚡ Quick Reference

GoalPattern / API
Between n and m digits\d{n,m}
Field length limits/^.{min,max}$/
Zero or one (optional)? or {0,1}
Exactly n{n} or {n,n}
At least n (no max){n,} — see {X,} tutorial
Lazy (minimal) range{n,m}?

📋 Brace Quantifier Family

Pick the brace form that matches your repetition rule.

Exact
a{3}

Exactly three

At least
a{3,}

Three or more

Range
a{2,4}

Two, three, or four

Optional
a{0,1}

Same as a?

Examples Gallery

Open DevTools Console (F12) or use Try-it links. Examples cover digit range validation, greedy matching within bounds, grouped repetition, password length rules, and hex color patterns.

📚 Getting Started

Validate values within a repetition range.

Example 1 — Validate Two to Four Digits with ^\d{2,4}$

Accept whole values that contain only digits and fall within the range.

JavaScript
const rule = /^\d{2,4}$/;



["12", "123", "1234", "12345", "1"].forEach((s) => {

  console.log(s, rule.test(s));

});

// 12    true

// 123   true

// 1234  true

// 12345 false

// 1     false
Try It Yourself

How It Works

{2,4} sets inclusive bounds. Anchors ensure the entire string is measured. Values below two digits or above four fail, while 12 through 1234 pass.

📈 Practical Patterns

Greedy runs, groups, and real-world formats.

Example 2 — Greedy Match Within Range

See how \d{2,4} picks the longest allowed digit run inside a string.

JavaScript
console.log("12345".match(/\d{2,4}/));  // ["1234"]

console.log("99".match(/\d{2,4}/));      // ["99"]

console.log("1".match(/\d{2,4}/));       // null



console.log("aaaa".match(/a{1,3}/g));    // ["aaa", "a"]
Try It Yourself

How It Works

Without anchors, the quantifier finds a substring. Greedy matching takes four digits from "12345", not two or three. With g, the engine continues after each match, producing multiple runs from "aaaa".

Example 3 — Group Range with (ha){2,3}

Match ha repeated two or three times as a unit.

JavaScript
const words = ["ha", "haha", "hahaha", "hahahaha"];



words.forEach((w) => {

  console.log(w, /(ha){2,3}/.test(w));

});

// ha        false — only one unit

// haha      true  — exactly two

// hahaha    true  — exactly three

// hahahaha  true  — contains hahaha (3 units)
Try It Yourself

How It Works

Parentheses treat ha as one token. The range counts full group repetitions. Single "ha" fails; two or three units pass. Longer strings may contain a valid substring inside.

Example 4 — Password Length Between 8 and 64 Characters

Enforce minimum and maximum length for an entire field.

JavaScript
const rule = /^.{8,64}$/;



console.log(rule.test("short"));       // false — too short

console.log(rule.test("longenough"));  // true

console.log(rule.test("a".repeat(64))); // true — at max

console.log(rule.test("a".repeat(65))); // false — over max
Try It Yourself

How It Works

The dot matches any character; {8,64} bounds total length. This checks size only—add separate rules for uppercase, digits, or symbols as needed.

Example 5 — Hex Color with {3,6} Digits

Match CSS-style hex colors with three to six hex characters after #.

JavaScript
const colors = ["#abc", "#abcdef", "#ab", "#ghijkl"];



colors.forEach((c) => {

  console.log(c, /#[0-9a-fA-F]{3,6}/.test(c));

});

// #abc      true

// #abcdef   true

// #ab       false — too short

// #ghijkl   false — g is not hex
Try It Yourself

How It Works

The character class limits symbols to hex digits; {3,6} enforces valid shorthand (#rgb) and full (#rrggbb) lengths. Invalid characters fail even if length is correct.

🚀 Common Use Cases

  • Field length limits — usernames, passwords, and comments with min/max character counts.
  • Numeric codes — product codes or PINs that must be within a digit range.
  • Hex and binary formats — color codes, hashes, or encoded values with variable but bounded width.
  • Optional suffixes{0,1} or ? for optional letters like British/American spelling.
  • Repeated units — grouped patterns that may repeat a limited number of times.
  • Input sanitization — flag values that exceed expected repetition bounds in log data.

Important Considerations

  • Min ≤ max{4,2} is invalid; JavaScript throws SyntaxError when creating the RegExp.
  • Greedy default{n,m} prefers the maximum count; use {n,m}? for minimal matching.
  • Group precedenceab{2,4} repeats only b; use (ab){2,4} for the full pair.
  • Substring vs whole field — add ^…$ when the entire input must satisfy the range.
  • Not semantic validation — length-range regex does not verify content quality or meaning.
  • Prefer ? for optional{0,1} and ? are equivalent; ? is usually more readable.

🧠 How the {X,Y} Quantifier Works

1

Match minimum

The engine repeats the token until it reaches at least n consecutive matches.

Floor
2

Extend up to max

While still under m and characters keep matching, greedy mode consumes more.

Ceiling
3

Stop at limit

Once m repetitions are reached, the quantifier stops even if more characters would match.

Bound
4

Backtrack if needed

If the rest of the pattern fails, the engine may retry with fewer repetitions within the allowed range.

📝 Notes

  • ? is shorthand for {0,1}; see the ? quantifier page.
  • Previous topic: {X,} at-least quantifier.
  • Exact count: {X} and {n,n} equivalence.
  • Lazy variant: {n,m}? matches as few repetitions as possible.
  • Pair with ^ and $ for whole-field range validation.
  • This completes the brace quantifier family: {n}, {n,}, and {n,m}.

Browser & Runtime Support

The {n,m} range quantifier is part of core JavaScript regular expression syntax.

Baseline · ES3+

RegExp {n,m} quantifier

Supported in every browser and Node.js version. Use {n,m} when both minimum and maximum repetition matter.

99% Universal syntax
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
{n,m} Excellent

Bottom line: Safe everywhere. {n,m} is the standard way to bound repetition between two counts.

Conclusion

The {X,Y} quantifier matches the previous token between X and Y times, inclusive. It completes the brace quantifier family alongside {n} (exact) and {n,} (at least). Use it for password length, numeric code ranges, hex colors, and any rule with both a floor and a ceiling.

Remember greedy defaults, valid min/max order, and anchors for whole-field checks. You now have the full brace toolkit for controlling repetition in JavaScript regular expressions.

💡 Best Practices

✅ Do

  • Use {n,m} when both minimum and maximum length matter
  • Combine ^…$ for whole-field range validation
  • Wrap repeating sequences in (…){n,m}
  • Prefer ? over {0,1} for optional tokens
  • Try {n,m}? when greedy matching takes too many characters

❌ Don’t

  • Write {max,min} with the larger number first—it throws
  • Use {n,m} when only exact or minimum rules apply
  • Forget anchors when validating entire input length
  • Write ab{2,4} when you mean (ab){2,4}
  • Rely on regex length checks alone for password security

Key Takeaways

Knowledge Unlocked

Five things to remember about the RegExp {X,Y} quantifier

Bound repetition between a minimum and maximum.

5
Core concepts
📈 02

{0,1}

Same as ?.

Shorthand
📄 03

{n,n}

Exact n.

Compare
🔒 04

^.{8,64}$

Length cap.

Validate
🚫 05

Min ≤ max

Required.

Pitfall

❓ Frequently Asked Questions

The {X,Y} quantifier (replace X and Y with numbers, such as {2,4}) means between X and Y repetitions of the preceding token, inclusive. Example: \d{2,4} matches two, three, or four digits in a row.
{n} requires exactly n repetitions. {n,} requires at least n with no maximum. {n,m} sets both a minimum n and a maximum m, giving you a bounded range.
Yes. The ? quantifier means zero or one repetition, which is equivalent to {0,1}. Both are greedy by default; use ?? or {0,1}? for lazy matching.
{n,n} is the same as {n}—exactly n repetitions. For example, {2,2} matches only aa, just like {2}.
Yes. (ab){2,4} matches ab repeated two, three, or four times: abab, ababab, or abababab. Parentheses make the whole group the repeated token.
Bounded range quantifiers are core JavaScript regex syntax since ES3. They work in every browser and Node.js version without polyfills.
Did you know?

All three brace quantifier forms work together as a family: {n} for exact counts, {n,} for open-ended minimums, and {n,m} for bounded ranges. The single-character quantifiers ?, +, and * are just shorthand for {0,1}, {1,}, and {0,}.

Explore the RegExp tutorial hub

Review all JavaScript regular expression topics in one place.

RegExp overview →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful