Borislav Hadzhiev
Thu Oct 21 2021·2 min read
Photo by Nathan Anderson
To count the words in a string:
split()
method on the string, passing it a string containing a
space as a parameter.length
property to get the number of words in the string.function countWords(str) { const arr = str.split(' '); return arr.filter(word => word !== '').length; } console.log(countWords('One two three')); // 👉️ 3 console.log(countWords('This is a long string')); // 👉️ 5
We created a reusable function, which takes a string as a parameter and returns the number of words in the string.
We use the String.split method and split the string on the spaces.
This returns an array containing the words in the string.
// 👇️ ['hello', 'world'] console.log('hello world'.split(' ')); // 👇️ ['one', 'two', 'three'] console.log('one two three'.split(' '));
// 👇️ ['hello', '', 'world'] console.log('hello world'.split(' ')); // 👇️ ['one', '', 'two', '', 'three'] console.log('one two three'.split(' '));
To make sure we don't count empty strings as words, we use the
Array.filter
method to filter empty strings out, before accessing the length
property on
the array.
The function we passed to the filter
method gets called with each element in
the array.
filter
method returns.We check if each element is NOT equal to an empty string and if the condition is met, the element gets added to the new array.
const arr = ['one', '', 'two', '']; const filtered = arr.filter(element => element !== ''); // 👇️ ['one', 'two'] console.log(filtered);
The last step is to access the length
property on the array and get the word
count.
Here's the complete example.
function countWords(str) { const arr = str.split(' '); return arr.filter(word => word !== '').length; } console.log(countWords('Walk the dog')); // 👉️ 3 console.log(countWords('Buy groceries')); // 👉️ 2