Last Updated : 11 Jul, 2025
The [0-9] expression in JavaScript regular expressions matches any single digit between 0 and 9. It is a character class used to represent a range of numeric characters.
JavaScript
let regex = /[0-9]/g;
let str = "abc123xyz";
let matches = str.match(regex);
console.log(matches);
The pattern [0-9] matches the digits 1, 2, and 3 in the string.
Syntax:/[0-9]/
let regex = /[0-9]/g;
let str = "Contact: 555-123-4567";
let matches = str.match(regex);
console.log(matches);
[ '5', '5', '5', '1', '2', '3', '4', '5', '6', '7' ]2. Extracting Numbers JavaScript
let regex = /[0-9]+/g;
// Matches one or more digits
let str = "The order IDs are 123, 456, and 789.";
let matches = str.match(regex);
console.log(matches);
[ '123', '456', '789' ]
The + quantifier ensures that consecutive digits are matched as a single number.
3. Validating Numeric Input JavaScript
let regex = /^[0-9]+$/;
let input = "123456";
if (regex.test(input)) {
console.log("Valid numeric input.");
} else {
console.log("Invalid input.");
}
Valid numeric input.
The pattern ^[0-9]+$ ensures the entire string consists only of digits.
4. Matching Numbers in a Date JavaScript
let regex = /[0-9]{4}/;
// Matches exactly four digits
let str = "The year is 2024.";
let match = str.match(regex);
console.log(match);
[ '2024', index: 12, input: 'The year is 2024.', groups: undefined ]
Here, [0-9]{4} matches a four-digit sequence representing a year.
5. Replacing Digits JavaScript
let regex = /[0-9]/g;
let str = "Room 101";
let result = str.replace(regex, "*");
console.log(result);
This example replaces all digits in the string with asterisks (*).
Common Patterns Using [0-9]/[0-9]/
/[0-9]+/
/[0-9]{3}/ // Matches exactly 3 digits
/^[0-9]+/
/\b[0-9]+\b/Comparison: [0-9] vs \d
For strict numeric matching, [0-9] is often preferred.
Why Use [0-9]?The [0-9] expression is a fundamental building block in JavaScript regex, perfect for handling numeric data in strings.
Recommended Links:RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4