JavaScript Program To Count The Frequency Of Given Character In String.

Frequency Of Given Character In String.

In this program, we will learn how to count the frequency of a given character in a string.

First Approach.

var str = 'hello world'.toLowerCase();
var char = 'l';
let frequency = 0;
for(let i=0;i<str.length;i++){
    if(str[i].toLo == char){
        frequency++;
    }
    
}

console.log('Frequency of' + ' ' + char + ' in ' + str + ' is', frequency);

Output: Frequency of l in hello world is 3 .

Second Approach.

var str = 'heLlo world'.toLowerCase();
var char = 'h';
var frequency = str.split(char).length-1;
console.log('Frequency of' + ' ' + char + ' in ' + str + ' is', frequency);

Output : Frequency of l in hello world is 3.

Back to top button