Home / Snippets / How to Count Total Words in JavaScript
How to Count Total Words in JavaScript cover

How to Count Total Words in JavaScript

89

2 years ago

0 comments

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

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this