How to count the words in a String in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 21 20212 min read

Count the words in a String #

To count the words in a string:

  1. Call the split() method on the string, passing it a string containing a space as a parameter.
  2. The split method will return an array of the string's words, on which you can access the length property to get the number of words in the string.
index.js
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.

index.js
// ๐Ÿ‘‡๏ธ ['hello', 'world'] console.log('hello world'.split(' ')); // ๐Ÿ‘‡๏ธ ['one', 'two', 'three'] console.log('one two three'.split(' '));
However, if the string contains a double space, this approach would split on the first space and add an empty string to the array.
index.js
// ๐Ÿ‘‡๏ธ ['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.

If the function returns a truthy value, the elements gets added to the new array that the 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.

index.js
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.

index.js
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

Further Reading #

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