How to count the words in a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Count the words in a String #

To count the words in a string:

  1. Use the String.split() method to split the string into an array of words.
  2. Access the length property on the array.
  3. The length property will return 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 that takes a string as a parameter and returns the number of words in the string.

We used the String.split method to split the string on each space.

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 multiple spaces next to one another, this approach would split on the first space and would then add empty strings to the array.
index.js
// 👇️ ['hello', '', 'world'] console.log('hello world'.split(' ')); // 👇️ ['one', '', 'two', '', 'three'] console.log('one two three'.split(' '));

We can use the Array.filter method to make sure we don't count empty strings as words.

The filter method enables us 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.

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

We check if each element is NOT equal to an empty string and return the result.

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 to get the word count.

Here's the complete code snippet.

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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.