Counting number of words in a sentence in JavaScript


We are required to write a JavaScript function that takes in a string. Our function is supposed to count the number of alphabets (uppercase or lowercase) in the array.

For example − If the input string is −

const str = 'this is a string!';

Then the output should be −

13

Example

The code for this will be −

const str = 'this is a string!';
const isAlpha = char => {
   const legend = 'abcdefghijklmnopqrstuvwxyz';
   return legend.includes(char);
};
const countAlphabets = (str = '') => {
   let count = 0;
   for(let i = 0; i < str.length; i++){
      if(!isAlpha(str[i])){
         continue;
      };
      count++;
   };
   return count;
};
console.log(countAlphabets(str));

Output

And the output in the console will be −

13

Updated on: 24-Nov-2020

366 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements