Borislav Hadzhiev
Last updated: Jul 24, 2022
Check out my new book
To count the spaces in a string:
split()
method to split the string on each space.length
property on the array and subtract 1.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(' '));
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:
length
property to get the string's length.String.replaceAll()
method to remove all spaces from the string.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:
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.