Skip to content

Word & Character Counter — TypeScript source

Live word, character, sentence, and paragraph counts plus reading-time estimate as you type.

This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Pure word / character / sentence / paragraph counters + reading-time estimate.
// Deterministic and framework-free - the unit-test surface for the Word Counter tool.

/** Number of whitespace-separated words. Empty or whitespace-only input → 0. */
export function countWords(t: string): number {
  return t.trim().split(/\s+/).filter(Boolean).length;
}

/** Total character count including whitespace (string length). */
export function countChars(t: string): number {
  return t.length;
}

/** Character count excluding all whitespace. */
export function countCharsNoSpaces(t: string): number {
  return t.replace(/\s/g, '').length;
}

/** Number of sentences: non-empty text terminated by one or more of . ! ? */
export function countSentences(t: string): number {
  return (t.match(/[^.!?]+[.!?]+/g) || []).length;
}

/** Number of paragraphs separated by one or more blank lines. */
export function countParagraphs(t: string): number {
  return t.split(/\n{2,}/).filter((s) => s.trim()).length;
}

/** Estimated reading time in minutes at 200 wpm. 0 for empty input, otherwise ≥ 1. */
export function readingTimeMin(words: number): number {
  if (words <= 0) return 0;
  return Math.max(1, Math.round(words / 200));
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →