JavaScript RegExp \d Metacharacter

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Digit 0–9

What You’ll Learn

The \d metacharacter matches any single digit from 0 through 9. It is shorthand for [0-9] and appears in nearly every pattern that validates numbers, extracts digits, or parses formatted text like phone numbers and dates.

01

Digit

\d

02

Shorthand

[0-9]

03

One char

Single digit

04

Quantifiers

\d+

05

Opposite

\D

06

Validate

\d{4}

Introduction

Many real-world strings mix letters and numbers: order IDs, ages, prices, and verification codes. The \d metacharacter gives you a compact way to target digits without listing every numeral.

One \d matches exactly one digit. To match a full number, combine \d with quantifiers like + (one or more) or {n} (exactly n digits).

Understanding the \d Metacharacter

\d is a predefined character class escape. In JavaScript it matches ASCII digits 0 through 9 only.

JavaScript
/\d/.test("abc");     // false (no digits)
/\d/.test("room 5");  // true  ("5" matches)

"price: $19".match(/\d+/);  // ["19"]
/\d{3}/.test("pin 482");    // true  (482 is three digits)

The uppercase form \D matches any character that is not a digit—equivalent to [^0-9].

💡
Beginner Tip

When you need a four-digit PIN, write /^\d{4}$/. The anchors ensure the entire string is exactly four digits—no letters before or after.

How to Use \d in JavaScript

Use \d in detection, extraction, validation, and replacement workflows:

JavaScript
/\d/.test("Order #42");              // true
"abc123def456".match(/\d+/g);        // ["123", "456"]
/^\d{4}$/.test("2026");              // true (four-digit year)
"Card 4111".replace(/\d/g, "*");     // "Card ****"

Pair \d with anchors (^, $), quantifiers (+, {n}), and grouping for structured formats like dates and phone numbers.

📝 Syntax

JavaScript
\d              // one digit 0–9
\d+             // one or more digits
\d{4}           // exactly four digits
\d*             // zero or more digits
\D              // one non-digit character

Common patterns

  • /\d+/ — match a run of digits (a number token).
  • /^\d{4}$/ — validate a four-digit code.
  • /\d{2}-\d{2}-\d{4}/ — match DD-MM-YYYY style dates.
  • /\D+/ — match non-digit sequences (words, symbols).

⚡ Quick Reference

GoalPattern
One digit\d
Number sequence\d+
Exactly 4 digits\d{4}
All digits only/^\d+$/
Non-digit char\D
Same as \d[0-9]

📋 \d vs [0-9] vs \D

Three related patterns for digits and non-digits.

Digit
\d

Shorthand

Class
[0-9]

Equivalent

Not digit
\D

Opposite

Many digits
\d+

Quantifier

Examples Gallery

Open DevTools Console (F12) or use Try-it links. Examples cover detection, extraction, validation, masking, and non-digit matching.

📚 Getting Started

Detect whether a string contains any digit.

Example 1 — Test for Any Digit

Return true when at least one numeral appears in the text.

JavaScript
console.log(/\d/.test("hello"));       // false
console.log(/\d/.test("room 5"));      // true
console.log(/\d/.test("Order #42"));   // true
Try It Yourself

How It Works

A single \d matches one digit anywhere in the string. Letters alone never satisfy the pattern.

📈 Practical Patterns

Extract, validate, mask, and filter with digit patterns.

Example 2 — Extract All Number Sequences

Pull every run of consecutive digits from mixed text.

JavaScript
const text = "Order 42 costs $19.99 today";

const numbers = text.match(/\d+/g);
console.log(numbers); // ["42", "19", "99"]

const first = text.match(/\d+/);
console.log(first[0]); // "42"
Try It Yourself

How It Works

\d+ greedily collects consecutive digits. Decimal points split 19.99 into two matches because . is not a digit.

Example 3 — Validate a Four-Digit PIN

Ensure input is exactly four digits and nothing else.

JavaScript
const pinPattern = /^\d{4}$/;

console.log(pinPattern.test("4829"));   // true
console.log(pinPattern.test("482"));    // false (too short)
console.log(pinPattern.test("48291"));  // false (too long)
console.log(pinPattern.test("48a9"));   // false (letter)
Try It Yourself

How It Works

^ and $ anchor the match to the full string. \d{4} requires exactly four digit characters in a row.

Example 4 — Mask Every Digit for Privacy

Replace each digit with an asterisk in a card or ID string.

JavaScript
const card = "Card ending 4111";

const masked = card.replace(/\d/g, "*");
console.log(masked); // "Card ending ****"
Try It Yourself

How It Works

The global flag with /\d/g replaces every digit individually. Non-digit characters stay unchanged.

Example 5 — Match Non-Digits with \D

Extract letter sequences by matching everything that is not a digit.

JavaScript
const mixed = "abc123def456";

const letters = mixed.match(/\D+/g);
console.log(letters); // ["abc", "def"]

console.log(/\D/.test("123"));  // false (all digits)
console.log(/\D/.test("a1"));   // true  ("a" is non-digit)
Try It Yourself

How It Works

\D is the inverse of \d. Use it to strip or isolate non-numeric content from mixed strings.

🚀 Common Use Cases

  • PIN and OTP validation — enforce fixed-length numeric codes with \d{n}.
  • Price parsing — extract digit runs from currency strings.
  • Form input rules — require at least one digit in passwords or usernames.
  • Data masking — hide digits in logs and UI displays.
  • Date fragments — match DD, MM, or YYYY segments in formatted dates.
  • Filtering — remove digits with replace(/\d/g, "") to keep letters only.

Important Considerations

  • One vs many — lone \d matches one digit; use + or {n} for sequences.
  • ASCII only — default \d does not match Unicode numerals like ① without the u flag and \p{Nd}.
  • Decimals\d+ stops at the decimal point; use \d+\.\d+ for simple floats.
  • Leading zeros\d+ preserves leading zeros in the matched string (e.g. "007").
  • Same as [0-9] — pick one style and stay consistent within a codebase.

🧠 How \d Matches Digits

1

Read character

The engine inspects the next character at the current position.

Scan
2

Check 0–9

\d succeeds only if the character is an ASCII digit.

Match
3

Apply quantifier

With + or {n}, the engine repeats the digit check.

Extend
4

Continue pattern

Digit matched → advance. Not a digit → fail or backtrack.

📝 Notes

  • \d equals [0-9] in standard JavaScript regex.
  • \D equals [^0-9] (any non-digit).
  • Review [0-9] character class and [^0-9] negated form.
  • Next up: . (dot) metacharacter for any character.
  • For integers only, anchor with ^\d+$; for decimals add \. between digit groups.
  • Combine with \b for whole-number tokens: \b\d+\b.

Browser & Runtime Support

The \d digit metacharacter is part of core JavaScript regular expression syntax.

Baseline · ES3+

RegExp \d

Supported in every browser and Node.js version. \d and [0-9] behave identically for ASCII digits.

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
\d Excellent

Bottom line: Safe everywhere. Use \d as the standard shorthand for matching digits 0–9.

Conclusion

The \d metacharacter is the fastest way to match digits in JavaScript regular expressions. It covers 0 through 9, pairs naturally with quantifiers and anchors, and has a clear inverse in \D.

Use \d+ to extract numbers, /^\d{n}$/ to validate fixed-length codes, and remember that it matches ASCII digits only by default. Next, learn the . (dot) metacharacter.

💡 Best Practices

✅ Do

  • Use \d+ for number tokens in mixed text
  • Anchor with ^ and $ for exact numeric input
  • Use \d{n} for fixed-length codes (PIN, OTP)
  • Pair with \b for standalone numbers
  • Know that \d and [0-9] are equivalent

❌ Don’t

  • Expect \d alone to match multi-digit numbers
  • Assume Unicode numerals match without the u flag
  • Forget the global flag when replacing all digits
  • Use \d+ for decimals without handling the dot
  • Mix \d and manual [0-9] randomly in one project

Key Takeaways

Knowledge Unlocked

Five things to remember about RegExp \d

Match digits 0 through 9 in JavaScript patterns.

5
Core concepts
📝 02

= [0-9]

Same set.

Compare
📈 03

\d+

Sequences.

Quantifier
🔒 04

\d{4}

PIN rule.

Validate
🚫 05

\D

Not digit.

Inverse

❓ Frequently Asked Questions

\d matches any single ASCII digit from 0 through 9. It is shorthand for the character class [0-9] and is one of the most common regex building blocks.
Yes, for standard JavaScript regex without the u (Unicode) flag, \d and [0-9] both match digits 0–9. Choose whichever is clearer in your pattern.
By itself, \d matches exactly one digit. Add a quantifier like + for one or more (\d+) or {4} for exactly four (\d{4}) to match longer number sequences.
\D is the opposite of \d—it matches any single character that is NOT a digit. It is equivalent to [^0-9] in JavaScript.
In default JavaScript regex, \d matches ASCII 0–9 only. Full Unicode digit categories require the u flag and \p{Nd} property escapes on modern engines.
The \d digit shorthand is core regex syntax since ES3. It works in every browser and Node.js version.
Did you know?

JavaScript also provides \w (word character: letters, digits, underscore) and \s (whitespace). Together with \d, these three shorthand classes cover most basic parsing tasks without writing full character classes.

Continue to . dot metacharacter

Learn how the dot matches almost any single character in a pattern.

. 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