JavaScript RegExp {X} Quantifier

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Exact count

What You’ll Learn

The {X} quantifier matches the previous token exactly X times. Replace X with a number: \d{4} means four digits, (ab){2} means abab. Use it when length matters—ZIP codes, years, PINs, and structured IDs.

01

{n}

Exact count

02

\d{4}

Four digits

03

(ab){2}

Group repeat

04

^…$

Full field

05

vs + *

Fixed length

06

{X,}

Next topic

Introduction

Sometimes “one or more” is too loose. A US ZIP code has five digits. A year has four. A verification code might require exactly six characters. The {X} quantifier gives you that precision: it repeats the preceding token a fixed number of times—no more, no fewer.

Writing \d{4} is clearer than \d\d\d\d, especially for longer counts like \d{16} for card numbers. Combined with anchors (^ and $), {n} becomes a powerful validation tool for form fields and structured data.

Understanding the {X} Exact-Count Quantifier

Place {n} immediately after the token you want to repeat, where n is a non-negative integer. The engine requires exactly n consecutive matches of that token.

JavaScript
/\d{3}/.test("123");    // true  — exactly 3 digits found

/\d{3}/.test("12");      // false — only 2 digits

/\d{3}/.test("1234");    // true  — "123" is a valid 3-digit run



"a{3}".replace(/a{3}/, "X");  // "X" from "aaa"

Without anchors, {n} finds a substring of the right length anywhere in the input. For whole-field validation, wrap the pattern with ^ and $ so the entire value must match.

💡
Beginner Tip

In tutorials we write {X} as a placeholder. In real patterns, replace X with a number: {4}, {6}, {10}. The braces are literal syntax—always include both opening and closing braces.

How to Use the {X} Quantifier

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

JavaScript
/\d{4}/;              // four digits (year, PIN block)

/\w{6}/;              // six word characters

/(ha){3}/;            // hahaha

/^\d{5}$/;            // entire value is 5 digits

/\d{4}-\d{2}-\d{2}/;  // ISO-style date segments



"abc123def".match(/\d{3}/);  // ["123"]

Use test() for yes/no checks, match() to extract the exact-length substring, and ^…$ when the full input must conform to a fixed length.

📝 Syntax

JavaScript
token{n}           // exactly n repetitions of token

\d{4}              // four digits

\w{8}              // eight word chars

(ab){2}            // ab repeated twice

a{3}               // same as aaa

{0}                // zero times (rare; see ? and *)

Common patterns

  • /\d{4}/ — four-digit year or block in a longer string.
  • /^\d{5}$/ — US ZIP code (five digits only).
  • /\d{4}-\d{2}-\d{2}/ — date with fixed-width segments.
  • /(..){3}/ — three pairs of any two characters.
  • /^[A-Z]{2}\d{6}$/ — two letters followed by six digits.

⚡ Quick Reference

GoalPattern / API
Exactly n digits\d{n}
Exactly n word chars\w{n}
Repeat a group n times(group){n}
Whole field is n chars/^token{n}$/
One or more (not exact)+ or {1,} — see + tutorial
At least n (not exact){n,} — see next tutorial

📋 {n} Exact vs + / * Open-Ended

Choose fixed length when the count is known; use + or * when any run length is acceptable.

Exact
\d{4}

Exactly four digits

One or more
\d+

One digit up to any length

Zero or one
a?

Same as a{0,1}

Zero or more
a*

Same as a{0,}

Examples Gallery

Open DevTools Console (F12) or use Try-it links. Examples cover exact digit runs, grouped repetition, date segments, fixed-length validation, and extracting equal-width tokens with g.

📚 Getting Started

Match a precise number of repetitions.

Example 1 — Match Exactly Three Digits with \d{3}

Find a run of exactly three digits inside different strings.

JavaScript
const samples = ["12", "123", "1234", "abc123def"];



samples.forEach((s) => {

  console.log(s, s.match(/\d{3}/));

});

// 12          null

// 123         ["123"]

// 1234        ["123"]

// abc123def   ["123"]
Try It Yourself

How It Works

\d{3} requires exactly three consecutive digits. "12" is too short. In longer strings, the engine finds the first valid three-digit run—often not the whole string unless you add anchors.

📈 Practical Patterns

Groups, dates, validation, and extraction.

Example 2 — Repeat a Group Exactly with (ha){3}

Match hahaha by repeating the ha pair three times.

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



words.forEach((w) => {

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

});

// hahaha    true

// haha      false — only two ha units

// hahahaha  true  — contains hahaha
Try It Yourself

How It Works

Parentheses make ha a single token. {3} counts whole group repetitions, not individual letters. "hahahaha" contains "hahaha" as a substring, so the test passes.

Example 3 — Fixed-Width Date Segments

Match an ISO-style date with four-, two-, and two-digit parts.

JavaScript
const dates = ["2024-07-17", "24-7-17", "2024/07/17"];



dates.forEach((d) => {

  console.log(d, /\d{4}-\d{2}-\d{2}/.test(d));

});

// 2024-07-17  true

// 24-7-17     false — segments wrong width

// 2024/07/17  false — slashes, not hyphens
Try It Yourself

How It Works

Each {n} enforces segment width: four digits for year, two for month and day. Literal hyphens between quantifiers define the separator. This pattern checks shape, not calendar validity.

Example 4 — Validate a Five-Digit ZIP Code

Require the entire value to be exactly five digits using anchors.

JavaScript
const rule = /^\d{5}$/;



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

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

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

console.log(rule.test("9021a"));   // false — letter breaks digits
Try It Yourself

How It Works

^ and $ pin the match to the full string. \d{5} alone would match five digits inside longer text; anchors make this a true field validator.

Example 5 — Extract Four-Character Word Chunks

Use \w{4} with the global flag to find equal-width runs.

JavaScript
const text = "The quick brown fox";



console.log(text.match(/\w{4}/g));

// ["quic", "brow"]



console.log("hello world".match(/\w{4}/g));

// ["hell", "worl"]
Try It Yourself

How It Works

With g, the engine scans left to right, finding every four-character word run. Spaces break continuity, so "The" (three letters) is skipped and matching resumes at quic. For whole words, combine with \b boundaries.

🚀 Common Use Cases

  • Fixed-length codes — PINs, OTPs, and verification tokens with exact character counts.
  • Postal and ID formats — ZIP codes, product SKUs, and license segments with known widths.
  • Date and time parts — four-digit years and two-digit months or days in structured strings.
  • Hex and binary runs[0-9a-f]{6} for color codes or fixed-width hashes.
  • Padding patterns — detect exactly N repeated separator characters.
  • Protocol fields — fixed-width headers in logs or network packet formats.

Important Considerations

  • Substring vs whole field{n} alone matches inside longer text; add ^…$ for full-value validation.
  • Group precedenceab{2} repeats only b twice (abb); use (ab){2} for abab.
  • Not range syntax yet{n} is exact count; {n,m} and {n,} are separate topics.
  • Zero count{0} matches zero times (like optional); prefer ? for readability when zero or one is intended.
  • Large n values{100} is valid but can be harder to read; consider whether a simpler pattern exists.
  • Validation limits — shape matching with {n} does not guarantee semantic correctness (e.g. month 99 still matches \d{2}).

🧠 How the {X} Quantifier Works

1

Identify the token

The engine looks at the single character, class, or group immediately before {n}.

Token
2

Count repetitions

It tries to match that token exactly n times in a row at the current position.

Exact
3

Succeed or fail

If fewer than n matches are available, the quantifier fails. More than n may still succeed if only n are required and the rest of the pattern allows it.

Bound
4

Continue the pattern

After exactly n repetitions, matching moves to the next part of the regex—literals, anchors, or more quantifiers.

📝 Notes

  • {1} matches once—usually redundant unless grouping for clarity.
  • + is shorthand for {1,}; * for {0,}; ? for {0,1}.
  • Previous topic: ^ start anchor.
  • Next topic: {X,} at-least-n quantifier.
  • See \d for digit matching with exact counts.
  • Pair with $ and ^ for strict field validation.

Browser & Runtime Support

The {n} exact-count quantifier is part of core JavaScript regular expression syntax.

Baseline · ES3+

RegExp {n} quantifier

Supported in every browser and Node.js version. Use {n} when repetition count must be precise.

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} Excellent

Bottom line: Safe everywhere. {n} is the standard way to require exactly n repetitions.

Conclusion

The {X} quantifier matches the previous token exactly X times. It is ideal for fixed-width segments—years, ZIP codes, grouped syllables, and structured IDs. Write \d{4} instead of four separate \d tokens, and wrap with ^…$ when the whole field must conform.

Remember that {n} without anchors finds substrings; use groups when the whole sequence repeats; and explore {X,} when “at least n” is enough. Next up: the {X,} quantifier.

💡 Best Practices

✅ Do

  • Use {n} when the required count is fixed and known
  • Combine ^ and $ for whole-field length validation
  • Wrap repeating sequences in (…){n} when the group repeats
  • Prefer \d{4} over \d\d\d\d for readability
  • Document what each {n} segment represents in date or ID patterns

❌ Don’t

  • Assume {n} validates the entire string without anchors
  • Write ab{2} when you mean (ab){2}
  • Use {n} when any length is acceptable—use + or *
  • Confuse exact {n} with range {n,m} syntax
  • Trust regex shape alone for dates or IDs—validate semantics in code too

Key Takeaways

Knowledge Unlocked

Five things to remember about the RegExp {X} quantifier

Match exact repetition counts with confidence.

5
Core concepts
📈 02

\d{4}

Fixed width.

Digits
📄 03

(ab){2}

Group repeat.

Groups
🔒 04

^…$

Full field.

Validate
🚫 05

vs + *

Open-ended.

Compare

❓ Frequently Asked Questions

The {X} quantifier (written with a number instead of X, such as {4}) means exactly X repetitions of the preceding token. Example: \d{4} matches exactly four digits in a row. X must be a non-negative integer.
{3} matches exactly three repetitions—no more, no fewer. + matches one or more with no upper limit. So /a{3}/ matches only aaa, while /a+/ also matches a, aa, aaa, aaaa, and so on.
Yes. (ab){2} matches ab exactly twice: abab. The quantifier counts full group repetitions, not individual characters inside the group.
For matching purposes, a{3} and aaa are equivalent—they both require three letter a characters in a row. {n} is simply a compact way to write long exact repetitions, especially with larger numbers like \d{16}.
Combine {n} with start and end anchors: /^\d{5}$/ requires exactly five digits for the whole string. Without ^ and $, the pattern may match a substring of the correct length inside a longer value.
Exact-count quantifiers are core JavaScript regex syntax since ES3. They work in every browser and Node.js version without polyfills.
Did you know?

JavaScript’s short quantifiers are all sugar for brace forms: ? is {0,1}, + is {1,}, and * is {0,}. The plain {n} form has no single-character shortcut—because exact counts vary, you always write the number inside braces.

Continue to {X,} at-least-n quantifier

Learn how {X,} matches n or more repetitions.

{X,} quantifier tutorial →

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