JavaScript: How to Count Words in a String

Updated: February 22, 2023 By: Khue Post a comment

Counting the number of words in a string can be a useful task for various applications, such as analyzing text data or creating word games. This succinct, practical article will show you how to do so in JavaScript.

A Common Pitfall

To count the number of words in a given string, many people will do like this (and may receive WRONG results):

  1. Define a function that takes a string as an argument.
  2. Use the split() method to convert the string into an array of words using a specified separator, which in this case, is a space.
  3. Use the length property of the resulting array to get the number of words.

This approach has a crucial flaw. If the input string contains only whitespace characters, the output can be 2, 3, 4, or N (depending on the number of whitespace characters). This makes no sense at all.

The Right Way

If the input string consists only of whitespace characters, the word count should be 0 because there are no words in the string. Here are the proper steps:

  1. Define a function that takes a string as an argument.
  2. Use the split() method to convert the string into an array of words using a specified separator, which in this case, is a space.
  3. Use a loop to iterate through all the elements in the array. If an element is not a space or an empty string, it will count by 1.

Example:

const countWords = (str) => {
  const words = str.split(' ');

  let count = 0;
  for (let i = 0; i < words.length; i++) {
    if (words[i] !== '') {
      count++;
    }
  }
  return count;
};

const s1 = '  Sling Academy  ';
const s2 = 'Hello';
const s3 = 'one two     three       four';

console.log(`The number of words in "${s1}" is ${countWords(s1)}`);
console.log(`The number of words in "${s2}" is ${countWords(s2)}`);
console.log(`The number of words in "${s3}" is ${countWords(s3)}`);

Output:

The number of words in "  Sling Academy  " is 2
The number of words in "Hello" is 1

Using Regular Expression

Another correct way to create the countWords() function is to use a regular expression:

const countWords = (str) => {
  str = str.trim();
  const words = str.match(/\S+/g);
  return words.length;
};