JavaScript – Counting String Occurrences

Counting String Occurrences

In JavaScript, there are several ways to count the occurrences of some text or character in a string. If you need to find the occurrences of a single character, then using the charAt() method inside a loop is the easiest method. Consider the following code:

var string = "lorem ipsum dolor sit amet, consectetur adipisicing elit";
var count = 0;
for(var i=0; string.length > i; i++){
    if(string.charAt(i) == 'i'){
        ++count; 
    }
}
console.log(count);    // 7

In this code, we examine every character of the given string and compare it to “i”, and if they are equal the “count” variable will be increases by one. In the end, the number of occurrences is printed in the browser’s console. This method is ideal for finding the occurrences of a single character, but if you need to find more than one character, you need another method. Consider this code:

var someString = "Lorem ipsum dolor sit amet, consectetur adipisicing elit";
var count = 0;
var pos = someString.indexOf("ip");
while(pos > -1){
    ++count;
    pos = someString.indexOf("ip", ++pos);
}
console.log(count);    // 2

Here, the indexOf() method is used to find the position of the first occurrence of “ip”, if there’s no “ip” in the string the result will be -1 which prevent the loop from executing, resulting in 0. Inside a while loop, the “count” variable is increases by one, and then we use indexOf() again to find the next occurrence.

Photo by Stephen Coles

Leave a Reply