Finding number of spaces in a string JavaScript



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
Updated on: 2020-11-25T05:23:36+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements