Finding number of spaces in a string JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a string containing spaces. The function should simply count the number of spaces present in that string.

For example −

If the input string is −

const str = 'this is a string';

Then the output should be −

const output = 4;

Example

const str = 'this is a string';
const countSpaces = (str = '') => {
   let count = 0;
   for(let i = 0;
   i < str.length; i++){
      const el = str[i];
      if(el !== ' '){
         continue; };
         count++; };
      return count;
};
console.log(countSpaces(str));

Output

This will produce the following output −

4
raja
Published on 25-Nov-2020 05:22:08
Advertisements