Posts Learn Components Snippets Categories Tags Tools About
/

How to Count Total Words in JavaScript

Learn how to easily count total words in JavaScript using simple regex function

Created on Nov 13, 2021

76 views

In this short snippet, you will learn How to Count Total Words in JavaScript. To count total words in JavaScript you can make use simple Regular Expression function. This solution will handle all of the possible cases and it's as efficient as possible.
text.split(/\S+/).length - 1;
Do refer to the full code example below for the implementation. (You don't want split(' ') unless you know beforehand that there are no spaces of greater length than one.)
var quote = `Lorem Ipsum is simply dummy text of the
    printing and typesetting industry. Lorem Ipsum has
    been the industry's standard dummy text ever since
    the 1500s, when an unknown printer took a galley of
    type and scrambled it to make a type specimen book. It
    has survived not only five centuries, but also the leap
    into electronic typesetting, remaining essentially unchanged.
    It was popularised in the 1960s with the release of Letraset
    sheets containing Lorem Ipsum passages, and more recently
    with desktop publishing software like Aldus PageMaker
    including versions of Lorem Ipsum.`;

function wordCount(text = '') {
  return text.split(/\S+/).length - 1;
};

console.log(wordCount(quote)); // 91
console.log(wordCount('a')); // 1
console.log(wordCount('  a ')); // 1
console.log(wordCount('   ')); // 0

Other Reads

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for How to Count Total Words in JavaScript

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Sponsors 👑

+ Add Yours
)