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