My Books

Text Processing with JavaScript

Solve complex text validation, extraction, and modification problems efficiently in JavaScript.

Modern Async JavaScript

Delve into async features of JavaScript from ES2020 through ESNext. Start building custom asynchronous iterators and generators, and more for fast, lean code.

JavaScript Brain Teasers

Ready to test your JavaScript skills? Challenge yourself with these brain-teasing puzzles, supercharge your learning journey, and emerge as a JavaScript pro.

JavaScript – 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. Let's look at some examples.

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, each character of the given string is examined and compared to i. If they are equal, the count variable will be increased 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 to use 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 the while loop, the count variable is increased by one, and then indexOf() is called again to find the next occurrence.

1 comment

Have your say