Sling Academy
Home/JavaScript/JavaScript: How to Count Words in a String

JavaScript: How to Count Words in a String

Last updated: February 22, 2023

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;
};

Next Article: JavaScript Regular Expressions: Extract & Validate URLs

Previous Article: JavaScript: 3 Ways to Create Multiline Strings

Series: JavaScript Strings

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration