How to count the occurrences in a string in JavaScript

In this tutorial, let’s look at how to count occurrences in a string in JavaScript. We’re going to first look at manually counting the occurrences using a loop, and then move on to methods that use pre-defined JavaScript functions.

Manually count the occurrences using a ‘for’ loop

If we were working with a character, a simple comparison operator would have done the trick. But, if you want a substring (more than one character) matched and if you want to know the number of occurrences of that substring in your given string, then you need to use the indexOf() method.

This method finds the index of the given character as well as the index of the first character of the given substring.

Also, you can start the check from a particular position.

Look at the below lines of code. For every iteration of the ‘for’ loop (which loops through the length of the string), we find the indexOf value of the substring at the ‘ith’ position, meaning, we’re starting the search from that position.

If the index this method returns is equal to the value of ‘i’, then we can be sure that our substring is occurring (starting) from that index, and we can count this match as a single instance/occurrence of the substring.

This method is foolproof because it’ll only return the index of the first character when the whole substring is encountered, and not before, so the chances of false positives are nil.

const countOccurrences = (str,substring) => {
    let count = 0;
    for(let i = 0; i < str.length; i++) {
        //find the index of the word starting at the current position/index, so would only count when the word starts, and won't count the subsequent characters in the word 
        if(str.indexOf(substring,i) === i) {
            count++;
        }
    }
    return count;
}

console.log(countOccurrences("Ba Ba Black Sheep Said Ba","Ba")); //3 

Find the occurrence of a character using a loop

On the other hand, if you’d like to search for the occurrence of a given character, you can use your good old ‘if’ statement with the equality comparison operator, as shown below:

const countOccurrences = (str,substring) => {
    let count = 0;
    for(let i = 0; i < str.length; i++) {
        if(str[i] === substring) {
            count++;
        }
    }
    return count;
}

console.log(countOccurrences("Ba Ba Black Sheep Said Ba","B")); //3 

Split the string on the substring

A quick trick to find the number of occurrences of a substring in JavaScript is by using the ‘split’ method. You can split the string based on the substring. Look at the example below.

const countOccurrences = (str,substring) => {
    str = str.split(substring);
    console.log(str); //['', ' ', ' Black Sheep Said ', '']
    return str.length;
}

console.log(countOccurrences("Ba Ba Black Sheep Said Ba","Ba")); //4 

As you can see, if we split the original string (“Ba Ba Black Sheep Said Ba”) based on the split condition ‘Ba’, we’ll get an array of length 4, where even the empty strings and spaces in between the word ‘Ba’, will be considered as separate elements of the array.

That’s great! But, if you notice, the number 4 is one more than the number of actual occurrences of ‘Ba’ in the string, which is 3.

So, to find the actual number of occurrences of the substring, we need to subtract the length of the resultant array by 1, as shown below:

    let count = str.split(substring).length - 1;
    return count; //3 

Use the ‘match’ method and regular expressions

You can also use the ‘match’ method since this method also returns an array with all the matches of the given condition.

In our case, we’ll be creating a simple regular expression where we just want to find exact matches for the given substring. Since we want to include every occurrence of the string in our resultant array, we’ve also added the ‘g’ flag, which refers to the global flag.

This flag finds every single match of the given regular expression in our string, as shown below:

let count = str.match(new RegExp(substring,'g'));
console.log(count); //['Ba', 'Ba', 'Ba'] 

So, in practice, to find the number of occurrences of the given substring, find the length of the array returned by the ‘match’ method, as shown below:

let count = str.match(new RegExp(substring,'g')).length; 

An algorithm with the replaceAll method

You can also go about things in a roundabout way by using the replaceAll method, or the ‘replace’ method with regular expressions and the global flag.

As you can see below, subtract the length of the string with the length of the string where the substring is replaced with nothing. Now, divide this result by the length of the substring.

This will return the number of occurrences of the substring in the string, as shown below:

const countOccurrences = (str,substring) => {
    let count = (str.length - (str.replaceAll(substring,'')).length ) / substring.length;
    return count;
}

console.log(countOccurrences("Ba Ba Black Sheep Said Ba","Ba")); //3 

Find the occurrences of a character using the ‘split’ and ‘filter’ methods

You can also find the number of occurrences of a character by splitting the string using the ‘split’ method. This method will split your string into an array of elements based on the split condition.

For instance, if you ask to split the string based on an empty string, every single character in the string, including spaces and special characters will form their own array element.

Now, you can use the ‘filter’ method on this array. This method can be used to filter an array based on a given condition.

It iterates through the entire array, and for every iteration, you get access to the element corresponding to that iteration.

Now, just filter all the elements that equate to the given character/substring. You’ll end up with a new array.
Find the length of this array to find the number of occurrences.

const countOccurrences = (str,substring) => {
return str.split('').filter(s => s === substring).length;
}

console.log(countOccurrences("Ba Ba Black Sheep Said Ba","B")); //3 

Find the occurrences of a word

Alternatively, you can find the occurrences of a word by using either a loop (‘for’, ‘forEach’, etc) or the ‘filter’ method we saw just now.

For this, first split the string based on a single space, so every single word gets its own array element.

Now, run the ‘forEach’ loop on this newly formed array. This loop works like the ‘filter’ method, but the only difference is that it doesn’t return anything. But, for every iteration, you can do some ‘calculation’ with the current element.

In our case, for every iteration, we’re going to check if the current element’s value is the same as the given substring.

If it is, increment the ‘count’ value by 1. That’s it!

const countOccurrences = (str,substring) => {
    let count = 0;
    //split the string based on words and form a new array 
    str = str.split(' '); //['Ba','Ba','Black','Sheep','Ba'];
    str.forEach((s) => {
        if(s === substring) {
            count++;
        }
    });
    return count;
}

console.log(countOccurrences("Ba Ba Black Sheep Said Ba","Ba")); //3 

You can also do what was done above by using the ‘filter’ method, as shown below:

const countOccurrences = (str,substring) => {
    return str.split(' ').filter(s => s === substring).length;
}

console.log(countOccurrences("Ba Ba Black Sheep Said Ba","Ba")); //3 

The ‘filter’ method filters through the array, and only those elements that match the substring make it to the newly formed ‘filtered’ array. Finally, we find the length of this new array to arrive at our desired value (number of occurrences of the substring).

Using the lodash library

The ‘lodash’ library comes with a lot of pre-defined methods that help in a lot of tasks.

In our case, we’re going to use the countBy method to count the number of occurrences of a character in a given string. Unfortunately, this method only works on characters. You’ll get ‘undefined’ for if you try to apply this to words or substrings of more than one character.

To start with, use the CDN link (Google the latest one, in case the one in this article gets outdated) in the section of your index.html file. Now, you have complete access to all the lodash methods from within your script files.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>JavaScript practice</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

</head>

<body>

    <script type="module" src="script.js"></script>
</body>
</html> 

Next, you can use the countBy method, send the string and substring to it in the format mentioned below, and you’re good to go.

const countOccurrences = (str,substring) => {
    return _.countBy(str)[substring];
}

console.log(countOccurrences("Ba Ba Black Sheep Said Ba","B")); //3 

That’s it! We’ve looked at the different ways to count the occurrences in a string in JavaScript.

Leave a Comment