JavaScript: Letter count within a string
JavaScript Function: Exercise-22 with Solution
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
Pictorial Presentation:

Sample Solution: -
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Letter count within a string</title>
</head>
<body>
</body>
</html>
JavaScript Code:
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'));
Sample Output:
2
Flowchart:

Live Demo:
See the Pen JavaScript - Letter count within a string-function-ex- 22 by w3resource (@w3resource) on CodePen.
Contribute your code and comments through Disqus.
Previous: Write a JavaScript function to get all possible subset with a fixed length (for example 2) combinations in an array.
Next: Write a JavaScript function to find the first not repeated character.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
JavaScript: Tips of the Day
Hide DOM Elements Dynamically
DOM elements can be done dynamically using JavaScript.
We can use the stykle.display property to do it.
For instance, we can write :
element.style.display = 'none';
It's the same as setting display: 'none'.
If we want to toggle them element back on, we can write:
element.style.display = 'block'
Ref: https://bit.ly/3mp5NgH
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises