Computer >> Computer tutorials >  >> Programming >> Javascript

How to print the number of times a specific character repeats in a statement in javascript?


The simplest way to find the number of times a character is repeated in a string in javascript is to iterate over the string and find all the character occurrences.

Example

let s = "hello world!";
let searchChar = "l";
let count = 0;
for(let i = 0; i < s.length; i ++) {
   if(s[i] == searchChar) {
      count ++;
   }
}
console.log(count)

Output

3