JavaScript program to find the occurrences of a character in a String
Following program shows you how to find the occurrences of a character in a string
function countString(str, letter) {
let count = 0;
// looping through the items
for (let i = 0; i < str.length; i++)
{
// check if the character is at that position
if (str.charAt(i) == letter)
{
count += 1;
}
}
return count;
}
// take input from the user
const string = 'this is a string';
const letterToCheck = 'i';
//passing parameters and calling the function
const result = countString(string, letterToCheck);
// displaying the result
console.log(result);
Output:
3
Try it Online here: https://onecompiler.com/javascript/3x6vym8gr