Count the Spaces in a String using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 24, 2022

banner

Check out my new book

Count the Spaces in a String #

To count the spaces in a string:

  1. Use the split() method to split the string on each space.
  2. Access the length property on the array and subtract 1.
  3. The result will be the number of spaces in the string.
index.js
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.

index.js
const str = 'one two three'; // 👇️ ['one', 'two', 'three'] console.log(str.split(' '));
We have to subtract 1 from the array's length to get the number of spaces in the string, because the space is the separator for the substring array.

An alternative is to use the String.replaceAll method.

To count the number of spaces in a string:

  1. Use the length property to get the string's length.
  2. Use the String.replaceAll() method to remove all spaces from the string.
  3. Subtract the length of the second string from the length of the original string.
index.js
const str = 'one two three'; const spaces2 = str.length - str.replaceAll(' ', '').length; console.log(spaces2); // 👉️ 2

We passed the following 2 arguments 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.

Note that the String.replaceAll method doesn't change the original string. Strings are immutable in JavaScript.

Which approach you pick is a matter of personal preference. I'd go with using replaceAll() because I find it more intuitive.

Use the search field on my Home Page to filter through my more than 3,000 articles.