Recipe 11.9

Counting Characters, Words, and Sentences

The Intl.Segmenter API breaks a string up into segments. The segment boundaries are determined by the segmenter’s configured granularity. You can configure a segmenter to segment the string by sentences, words, or individual characters (referred to by the API as graphemes).

This example uses Intl.Segmenter to generate a character, word, and sentence count as you type in the text area.

Demo

  • Characters: 0
  • Words: 0
  • Sentences: 0

Code

JavaScript
const editor = document.querySelector('#editor');
const characterCount = document.querySelector('#character-count');
const wordCount = document.querySelector('#word-count');
const sentenceCount = document.querySelector('#sentence-count');

const characters = new Intl.Segmenter(
  navigator.language,
  { granularity: 'grapheme' }
);

const words = new Intl.Segmenter(
  navigator.language,
  { granularity: 'word' }
);

const sentences = new Intl.Segmenter(
  navigator.language,
  { granularity: 'sentence' }
);

editor.addEventListener('input', () => {
  // The segmenters return iterables, which you can convert
  // into an array using spread syntax. Then you can get the length of
  // the array to find the count.
  characterCount.textContent = 
    [...characters.segment(editor.value)].length;
  wordCount.textContent = 
    [...words.segment(editor.value)].length;
  sentenceCount.textContent = 
    [...sentences.segment(editor.value)].length;
});
HTML
<textarea 
  placeholder="Enter some text..." 
  class="form-control" 
  id="editor"
></textarea>

<ul>
  <li>Characters: <span id="character-count">0</span></li>
  <li>Words: <span id="word-count">0</span></li>
  <li>Sentences: <span id="sentence-count">0</span></li>
</ul>
Web API Cookbook
Joe Attardi