Count the Spaces in a String using JavaScript


Borislav Hadzhiev

Mon Nov 15 20211 min read


Photo by Sam Carter

Count the Spaces in a String #

To count the spaces in a string, call the split() method on the string, passing it a string containing a space as a parameter. The split() method will return an array of substrings. Access the length property on the array and subtract 1 to get the number of spaces.

const str = 'one two three'; const spaces1 = str.split(' ').length - 1; console.log(spaces1); // ๐Ÿ‘‰๏ธ 2

The only parameter we passed to the String.split method is the separator.

The method returns an array of substrings.

const str = 'one two three'; // ๐Ÿ‘‡๏ธ ['one', 'two', 'three'] console.log(str.split(' '));

To get the number of spaces in the string, we have to subtract 1 from the array's length, because the space is the separator for the substring array.

An alternative is to use the String.replaceAll method.

const str = 'one two three'; const spaces2 = str.length - str.replaceAll(' ', '').length; console.log(spaces2); // ๐Ÿ‘‰๏ธ 2

We passed the following 2 parameters to the replaceAll method:

  1. The substring we want to replace
  2. The replacement for each match

The last step is to subtract the length of the string without any spaces from the string that contains spaces.

This is the more intuitive solution in my opinion, because subtracting 1 from the result of the split() method takes a second to understand.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee