Last Updated : 05 Dec, 2024
In JavaScript regular expressions, the \d metacharacter is used to match any digit character (0-9). This is a shorthand for the character class [0-9], which matches any single character within the specified range.
To begin, let's look at a simple example where we use \d to match digits in a string.
JavaScript
let s = "The year is 2024 and the month is 12.";
let regex = /\d+/g;
let match = s.match(regex);
console.log(match);
You can also use \d to match a single digit in a string. Let's see how to match only one digit.
JavaScript
let s = "The code 5 is valid, but 15 is too long.";
let regex = /\d/;
let match = s.match(regex);
console.log(match);
[ '5', index: 9, input: 'The code 5 is valid, but 15 is too long.', groups: undefined ]
You can combine the \d metacharacter with anchors like ^ (start of string) or $ (end of string) to match digits in specific positions in the string.
JavaScript
let s = "Year2024";
let regexS = /^\d+/;
let regexE = /\d+$/;
console.log(s.match(regexS));
console.log(s.match(regexE));
null [ '2024', index: 4, input: 'Year2024', groups: undefined ]
You can use \d to match digits in more complex patterns, like when digits are surrounded by non-digit characters.
JavaScript
let s = "Order123 has been shipped.";
let regex = /\d+/;
let match = s.match(regex);
console.log(match);
[ '123', index: 5, input: 'Order123 has been shipped.', groups: undefined ]
The \d metacharacter is frequently used for validating numerical patterns, such as checking if a string is a valid number or phone number.
JavaScript
let phone = "123-456-7890";
let regex = /^\d{3}-\d{3}-\d{4}$/;
let isValid = regex.test(phone);
console.log(isValid);
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