Counting the occurrences of a substring in a string is a common task in JavaScript programming. knowing how to efficiently count specific patterns can be incredibly useful. JavaScript offers multiple methods to achieve this, each with its own advantages and use cases.
There are many approaches to count occurrences of a substring in a string. In this post we will cover two approaches –
Methods to count occurrences of a substring in a string
- Using loop
- Using Regular Expressions
Using Loop
We can use a loop to iterate through the string and count the number of occurrences of the substring.
function countOccurrences(string, substring) {
let count = 0;
let currentIndex = 0;
while ((currentIndex = string.indexOf(substring, currentIndex)) !== -1) {
count++;
currentIndex += substring.length;
}
return count;
}
const inputString = "Hello, Hello, Hello, World!";
const searchSubstring = "Hello";
const occurrences = countOccurrences(inputString, searchSubstring);
document.write(`${searchSubstring} appears ${occurrences} times in the string.`);
Output of the above will be
Hello appears 3 times in the string.
We used the indexOf() method to search for the first occurrence of the substring in the string.
If the indexOf() method finds an occurrence (i.e., it returns a non-negative value), increment the count variable and update currentIndex to the position just after the found occurrence.
Using Regular Expressions
In this method, we use regular expressions to match and count occurrences of the substring.
function countOccurrences(string, substring) {
const regex = new RegExp(substring, 'g');
const matches = string.match(regex);
return matches ? matches.length : 0;
}
const inputString = "Hello, Hello, Hello, World!";
const searchSubstring = "Hello";
const occurrences = countOccurrences(inputString, searchSubstring);
document.write(`${searchSubstring} appears ${occurrences} times in the string.`);
Output of the above will be
Hello appears 3 times in the string.
In this example, we have created a regular expression object and passed the substring with the ‘g’ flag. The ‘g’ flag stands for “global,” which means it will find all matches in the string, not just the first one.
Then we used the match() method on the input string, passing the regular expression as an argument. This method returns an array of all matches found in the string.
Both approaches achieve the same result, but regular expressions can be more efficient and is often preferred for its readability and conciseness.