Finding the number of words in a string JavaScript


We are required to write a JavaScript function that takes in a string of any length. The function should then count the number of words in that string.

Example

const str = 'THis is an example string';
const findWords = (str = '') => {
   if(!str.length){
      return 0;
   };
   let count = 1;
   for(let i = 0; i < str.length; i++){
      if(str[i] === ' '){
         count++;
      };
   };
   return count;
};
console.log(findWords(str));

Output

And the output in the console will be −

5

Updated on: 23-Nov-2020

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements