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
Leave a reply