Skip to main content
Baldur Bjarnason

Word Count

Baldur Bjarnason

Here’s a quick and dirty locale-aware word count function that uses the standard Intl object and works in node and modern browsers:

function wordCount(text, lang = "en") {
  const segmenter = new Intl.Segmenter(lang, { granularity: "word" });
  const segments = Array.from(segmenter.segment(text)).filter(
    (entry) => entry.isWordLike,
  );
  return segments.length;
}

Not the fastest in the world but will accurately count words and ignore punctuation and white space for the given locale.