settingsAccountsettings
Menusettings

Q: Letter Occurrences in String in JS

+2 votes

Write a JS function that counts how many times a specific letter occurs in a given string.

The input comes in two string arguments:

  • The first element is the string to check
  • The second element is the letter to count.

The output should be returned as a result of your function.

Input:
'hello', 'l'

Output:
2


Input:
'panther', 'n'

Output:
1

asked in JavaScript category by user golearnweb
edited by user golearnweb

1 Answer

+2 votes
 
Best answer

Here is tha JavaScript code:

function countLetter(str, letter) {
    var count = 0;
    for (var i = 0; i < str.length; i++)
        if (str[i] == letter) {
            count++;
        }
    console.log(count);
}
countLetter("hello", "l");

 

answered by user nikole
edited by user golearnweb
...