Sometimes, we want to define a regular expression to match exactly 5 digits with JavaScript.
In this article, we’ll look at how to define a regular expression to match exactly 5 digits with JavaScript.
How to define a regular expression to match exactly 5 digits with JavaScript?
To define a regular expression to match exactly 5 digits with JavaScript, we can use the \d
pattern.
For instance, we write
const str = "f 34 545 323 12345 54321 123456";
const matches = str.match(/\b\d{5}\b/g);
console.log(matches);
to define the /\b\d{5}\b/g
pattern that matches groups of 5 digits.
\b
matches word bounddaries.
And \d{5}
matches 5 digits.
Then we call str.match
with the regex to return an array of all matches.
Conclusion
To define a regular expression to match exactly 5 digits with JavaScript, we can use the \d
pattern.