A common task in text processing and data validation is to count how many times a specific pattern appears in a string. For example, you might need to count the number of vowels, digits, or occurrences of a specific word. The most direct and idiomatic way to do this in JavaScript is with the String.prototype.match() method combined with a regular expression.
This guide will teach you how to use match() with the global flag to get all occurrences of a pattern and how to safely count them. We will also cover an alternative looping method using RegExp.prototype.exec().
The Core Method (Recommended): String.prototype.match()
The string.match() method is the best tool for this job. When used with a regular expression that has the global (g) flag, it returns an array of all matches. You can then simply get the length of that array.
For example, you have a string and need to count every occurrence of the word "apple". How to count the number of times "apple" appears?
// Problem: How to count the number of times "apple" appears?
const text = 'An apple a day keeps the doctor away. I love apple pie.';This clean, one-line solution is the best practice.
const text = 'An apple a day keeps the doctor away. I love apple pie.';
const pattern = /apple/gi; // g = global, i = case-insensitive
// The `|| []` is a safety net in case no matches are found.
const matches = text.match(pattern) || [];
const count = matches.length;
console.log(`The word "apple" appears ${count} times.`);Output:
The word "apple" appears 2 times.How the match() Method Works
- The Regex and the Global Flag (
g): The most critical part of this technique is thegflag on the regular expression. Without it,match()will only find the first occurrence. Theiflag for case-insensitivity is also commonly used. - The Return Value:
- If one or more matches are found,
match()returns an array containing all the matching substrings (e.g.,['apple', 'apple']). - If no matches are found,
match()returnsnull.
- If one or more matches are found,
- The Safety Net (
|| []): Becausematch()can returnnull, trying to access.lengthonnullwould throw aTypeError. The|| [](OR empty array) is a standard idiom that provides a safe fallback. Iftext.match(pattern)returnsnull, the expression becomesnull || [], which evaluates to[]. Getting the.lengthof an empty array is0, which is the correct count.
The Looping Alternative: RegExp.prototype.exec()
An alternative method, which is more manual but can be useful in some complex scenarios, is to use the exec() method in a while loop. The exec() method finds the next match in a string each time it's called.
const text = 'An apple a day keeps the doctor away. I love apple pie.';
const pattern = /apple/gi;
let count = 0;
let match;
// The loop continues as long as exec() keeps finding matches.
while ((match = pattern.exec(text)) !== null) {
count++;
}
console.log(`The word "apple" appears ${count} times.`);Output:
The word "apple" appears 2 times.Practical Examples with Common Regular Expressions
This technique is incredibly versatile. Here are a few examples of counting different patterns.
How to Count Digits
const str = 'User ID: 123, Item ID: 456';
const digitCount = (str.match(/[0-9]/g) || []).length;
console.log(`The string contains ${digitCount} digits.`);Output:
The string contains 6 digits.How to Count Vowels
const sentence = 'A quick brown fox';
const vowelCount = (sentence.match(/[aeiou]/gi) || []).length;
console.log(`The sentence contains ${vowelCount} vowels.`);Output:
The sentence contains 5 vowels.How to Count Words
const phrase = 'One two three.';
// `\b` is a word boundary, `\w+` is one or more word characters.
const wordCount = (phrase.match(/\b\w+\b/g) || []).length;
console.log(`The phrase contains ${wordCount} words.`);Output:
The phrase contains 3 words.Conclusion
For counting the number of regex matches in a string, modern JavaScript provides a clean and powerful solution.
- The
.match(/pattern/g).lengthmethod is the recommended best practice. It is declarative, concise, and highly readable. - Always include the global (
g) flag on your regular expression to ensure you find all occurrences, not just the first. - Always use the
|| []fallback to prevent aTypeErrorin cases where no matches are found. - The
exec()method in awhileloop is a functional alternative but is more verbose and generally unnecessary if you only need the total count.