How to Count Occurrences of a Substring in a String in JavaScript

How-to-Count-Occurrences-of-a-Substring-in-a-String-in-JavaScript

There are many approaches to count occurrences of a substring inside a string. In this post we will cover two approaches –

Methods

  • Using loop
  • Using Regular Expressions

Method 1 – 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.


Method 2 – 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.