- 1
9. Write a JavaScript function that accepts two arguments, a string and a letter and the function will count the number of occu
9. Write a JavaScript function that accepts two arguments, a string and a letter and the function will count the number of occurrences of the specified letter within the string. Sample arguments : 'w3resource.com', 'o' Expected output : 2 .
2 odpowiedzi
- 2
just make a loop that iterates through the string and check if the current character equals the second argument. If it is true, then add 1 to a variable storing the number of ocurrences. Once it iterates over the whole atring, return the variable.
- 2
function char_count(str, letter)
{
var letter_Count = 0;
for (var position = 0; position < str.length; position++)
{
if (str.charAt(position) == letter)
{
letter_Count += 1;
}
}
return letter_Count;
}
console.log(char_count('w3resource.com', 'o'));