JavaScript RegExp [0-9] Character Class

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

What You’ll Learn

The [0-9] character class matches any single digit from 0 through 9. It is one of the most common building blocks in JavaScript regex—used for parsing numbers, validating codes, and extracting digits from mixed text.

01

Class

[0-9]

02

One digit

0, 1, … 9

03

Like \d

ASCII digits

04

Quantifiers

+, {n}

05

Methods

test, match

06

Negate

[^0-9]

Introduction

Regular expressions let you describe text patterns. A character class (text inside square brackets) matches one character from a set you define. The range [0-9] is shorthand for “any digit.”

You will see it in phone validators, form field checks, log parsers, and anywhere JavaScript needs to find or verify numeric characters inside strings.

Understanding the [0-9] Character Class

Inside [ and ], a hyphen between two characters creates a range. 0-9 includes every digit character. The pattern matches exactly one digit per [0-9] token unless you add a quantifier.

JavaScript
/[0-9]/.test("7");   // true
/[0-9]/.test("a");   // false
/[0-9]/.test("42");  // true (matches the "4" only)

This is a character class, not a capture group. Parentheses ( ) create capturing groups; square brackets [ ] define which single character may appear at that position.

💡
Beginner Tip

To match a sequence of digits (like 2024), combine the class with + (one or more): /[0-9]+/. One [0-9] alone only consumes a single digit character.

How to Use [0-9] in JavaScript

Write the pattern as a literal or pass it to the RegExp constructor, then call standard methods:

JavaScript
const hasDigit = /[0-9]/.test("Room 4B");        // true
const firstDigit = "Room 4B".match(/[0-9]/);     // ["4"]
const digitsOnly = "a1b2c3".replace(/[^0-9]/g, ""); // "123"

Use test() for yes/no checks, match() to extract, and replace() to transform. Add the g flag when you need every digit, not just the first.

📝 Syntax

JavaScript
/[0-9]/              // one digit
/[0-9]+/             // one or more digits
/[0-9]{4}/            // exactly four digits
new RegExp("[0-9]")  // constructor form

Common quantifiers with [0-9]

  • [0-9]? — zero or one digit (optional).
  • [0-9]+ — one or more digits in a row.
  • [0-9]* — zero or more digits.
  • [0-9]{2,4} — between 2 and 4 digits.
  • ^[0-9]+$ — entire string must be digits only.

⚡ Quick Reference

GoalPattern
Any single digit[0-9] or \d
One or more digits[0-9]+ or \d+
Exactly 4 digits[0-9]{4}
Digits only (whole string)/^[0-9]+$/
Not a digit[^0-9] or \D
Strip non-digitsstr.replace(/[^0-9]/g, "")

📋 [0-9] vs \d

In JavaScript both match ASCII digits. Pick the form that reads best in your pattern.

Explicit
[0-9]

Clear range

Shorthand
\d

Compact

Negated
[^0-9] / \D

Non-digit

Unicode
ASCII only

In JS engine

Examples Gallery

Open DevTools Console (F12) or use Try-it links. Examples cover testing, extracting, validating, and replacing digits.

📚 Getting Started

Check whether text contains any digit.

Example 1 — Test for Any Digit with test()

Return true when the string contains at least one digit character.

JavaScript
const digitPattern = /[0-9]/;

console.log(digitPattern.test("hello"));    // false
console.log(digitPattern.test("Room 4B"));  // true
console.log(digitPattern.test("2024"));     // true
Try It Yourself

How It Works

test() scans the string for any position where [0-9] matches. It stops at the first digit found and returns true.

📈 Practical Patterns

Extract, validate, and clean digit sequences.

Example 2 — Find the First Digit with match()

Locate the first digit in mixed alphanumeric text.

JavaScript
const label = "Version 2.4.1";

const first = label.match(/[0-9]/);
console.log(first[0]);  // "2"

const all = label.match(/[0-9]/g);
console.log(all);       // ["2", "4", "1"]
Try It Yourself

How It Works

Without g, match() returns the first digit. With the global flag, it collects every individual digit match into an array.

Example 3 — Extract Full Number Sequences

Use [0-9]+ to grab entire numeric chunks from a sentence.

JavaScript
const log = "Order #1042 shipped on 2024-07-17 for $59";

const numbers = log.match(/[0-9]+/g);
console.log(numbers); // ["1042", "2024", "07", "17", "59"]
Try It Yourself

How It Works

The + quantifier repeats [0-9], so consecutive digits form one match. Date segments split at the hyphen because non-digits break the run.

Example 4 — Validate a Four-Digit PIN

Anchor the pattern so the entire input must be exactly four digits.

JavaScript
const pinPattern = /^[0-9]{4}$/;

function isValidPin(pin) {
  return pinPattern.test(pin);
}

console.log(isValidPin("1234"));   // true
console.log(isValidPin("12a4"));  // false
console.log(isValidPin("12345")); // false
Try It Yourself

How It Works

^ and $ anchor the match to the full string. {4} requires exactly four digit characters—no letters, spaces, or extra digits allowed.

Example 5 — Strip Non-Digits with replace()

Keep only digits by removing everything matched by the negated class [^0-9].

JavaScript
const phone = "(555) 123-4567";

const digitsOnly = phone.replace(/[^0-9]/g, "");
console.log(digitsOnly); // "5551234567"

// Mask digits in display text
const masked = phone.replace(/[0-9]/g, "*");
console.log(masked);     // (***) ***-****
Try It Yourself

How It Works

[^0-9] matches every character that is not a digit. Replacing those with "" leaves digits only. Replacing digits with * masks them for display.

🚀 Common Use Cases

  • Form validation — ensure fields contain digits (age, ZIP code, quantity).
  • Log parsing — extract IDs, timestamps, and numeric metrics from text logs.
  • Input sanitization — strip formatting characters from phone or card numbers.
  • Password rules — require at least one digit with a lookahead or simple test().
  • Data cleaning — pull numeric values from CSV-like strings before conversion.
  • Masking — hide digits in UI output for privacy.

Important Considerations

  • One vs many — bare [0-9] matches a single digit; add + or {n} for sequences.
  • ASCII digits only — in JavaScript, [0-9] and \d match 0–9 only, not other numeral systems (e.g. Arabic-Indic digits) unless you use Unicode-aware patterns.
  • Anchors matter — without ^ and $, [0-9]+ matches a substring anywhere in the text.
  • Hyphen placement — in other positions inside [ ], a hyphen can be literal; at the start or end it is safe: [-0-9] or [0-9-].
  • Not a number type — regex returns strings; use Number() or parseInt after extraction.

🧠 How [0-9] Matches Text

1

Build the class

Square brackets define a set. The range 0-9 expands to all ten digit characters.

Pattern
2

Scan the string

The engine walks the input left to right looking for a position where the next character is in the set.

Search
3

Apply quantifier

If you wrote + or {4}, the engine repeats the digit match that many times.

Repeat
4

Return result

Match found → true or matched text. No digit → null or false.

📝 Notes

  • [0-9] is equivalent to [0123456789] and to \d in JavaScript.
  • Use [^0-9] (or \D) for “anything except a digit.”
  • Combine with flags: /[0-9]/g for all digits, /[0-9]/i has no effect on digits.
  • For decimal numbers, consider /[0-9]+(\.[0-9]+)?/ to allow an optional fractional part.
  • See also RegExp exec() for reading capture groups from complex patterns.
  • Next in this series: [abc] character set for matching specific letters.

Browser & Runtime Support

The [0-9] character class is part of core JavaScript regular expression syntax and works identically across environments.

Baseline · ES3+

RegExp [0-9]

Supported in every browser and Node.js version. No polyfill needed for basic digit character classes.

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
[0-9] Excellent

Bottom line: Safe everywhere. Use [0-9] or \d confidently for ASCII digit matching in all JavaScript runtimes.

Conclusion

The [0-9] character class is a fundamental regex tool for matching digits in JavaScript. Combined with quantifiers and anchors, it powers validation, extraction, and cleaning tasks across web apps.

Start with /[0-9]/ for a single digit, /[0-9]+/g to find number runs, and /^[0-9]{n}$/ for exact-length numeric codes. When you need non-digits, reach for [^0-9] next.

💡 Best Practices

✅ Do

  • Add + or {n} when you need digit sequences
  • Use ^ and $ for full-string validation
  • Prefer \d when brevity helps readability
  • Convert extracted strings with Number() when needed
  • Test edge cases: empty input, letters only, mixed text

❌ Don’t

  • Assume [0-9] matches an entire number alone
  • Forget the g flag when you need all matches
  • Confuse [0-9] (class) with (0-9) (invalid/literal group)
  • Expect Unicode numerals to match without explicit ranges
  • Over-complicate simple digit checks with heavy regex

Key Takeaways

Knowledge Unlocked

Five things to remember about RegExp [0-9]

Match digits confidently in JavaScript patterns.

5
Core concepts
🔢 02

One digit

Per token.

Scope
🔄 03

Like \d

Same in JS.

Shorthand
04

+ quantifier

Full numbers.

Pattern
🚫 05

[^0-9]

Not a digit.

Negate

❓ Frequently Asked Questions

[0-9] is a character class that matches exactly one ASCII digit—any character from 0 through 9. Place it inside square brackets in your pattern: /[0-9]/.
In JavaScript, \d and [0-9] both match ASCII digits 0–9. They are interchangeable for basic digit matching. Use whichever reads clearer in your pattern.
By itself, [0-9] matches only one digit. Add a quantifier like + (one or more) or {4} (exactly four) to match longer number sequences: /[0-9]+/ or /[0-9]{4}/.
[0-9] matches a digit. [^0-9] matches any single character that is NOT a digit—the ^ inside brackets negates the class.
Yes. All standard RegExp methods work with character classes. test() checks for a match, match() extracts matches, and replace() substitutes matched digits.
Character classes have been part of JavaScript regular expressions since ES3. [0-9] works in every browser and Node.js version.
Did you know?

Character classes like [0-9], [a-z], and [abc] match exactly one character per class token. To match a literal hyphen inside a class, put it first or last: [-09] or [0-9-].

Continue to [abc] character class

Learn how to match any one character from a custom letter set inside square brackets.

[abc] 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