Finding how many time a specific letter is appearing in the sentence using for loop, break, and continue - JavaScript


We are required to write a JavaScript function that finds how many times a specific letter is appearing in the sentence

Example

Let’s write the code for this function −

const string = 'This is just an example string for the program';
const countAppearances = (str, char) => {
   let count = 0;
   for(let i = 0; i < str.length; i++){
   if(str[i] !== char){
      // using continue to move to next iteration
         continue;
      };
      // if we reached here it means that str[i] and char are same
      // so we increase the count
      count++;
   };
   return count;
};
console.log(countAppearances(string, 'a'));
console.log(countAppearances(string, 'e'));
console.log(countAppearances(string, 's'));

Output

Following is the output in the console −

3
3
4

Updated on: 14-Sep-2020

52 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements