Algorithm
-
Input: Accept the string and the character to be checked as input.
-
Initialize Counter: Set a counter variable to 0 to keep track of the number of occurrences.
-
Loop through the String: Use a loop to iterate through each character in the string.
a. Check if the current character is equal to the target character.
b. If true, increment the counter.
-
Output: Display or return the final count of occurrences.
Code Examples
#1 Code Example- Check Occurrence of a Character Using for Loop
Code -
Javascript Programming
// program to check the number of occurrence of a character
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 = prompt('Enter a string: ');
const letterToCheck = prompt('Enter a letter to check: ');
//passing parameters and calling the function
const result = countString(string, letterToCheck);
// displaying the result
console.log(result);
Copy The Code &
Try With Live Editor
Output
Enter a letter to check: o
2
#2 Code Example- Check occurrence of a character using a Regex
Code -
Javascript Programming
// program to check the occurrence of a character
function countString(str, letter) {
// creating regex
const re = new RegExp(letter, 'g');
// matching the pattern
const count = str.match(re).length;
return count;
}
// take input from the user
const string = prompt('Enter a string: ');
const letterToCheck = prompt('Enter a letter to check: ');
//passing parameters and calling the function
const result = countString(string, letterToCheck);
// displaying the result
console.log(result);
Copy The Code &
Try With Live Editor
Output
Enter a letter to check: o
2
Demonstration
JavaScript Programing Example to Check the Number of Occurrences of a Character in the String-DevsEnv