Skip to content
Tutorials Center
My learning

Topics

Lesson 141 of 156 Β· Projects

Project: Text Editor and Word Counter

Build a small text editor with a live word, character and reading-time counter, find and replace, undo-friendly editing and a download button using Blob.

Every writing tool shows a little status line: "312 words, 1,804 characters, 2 min read". In this project you will build a plain-text editor with exactly that status line, plus a few text tools (change case, tidy whitespace, find and replace) and a button that downloads your text as a .txt file.

You will practice string handling, regular expressions, the input event, Intl formatting and the Blob API. It builds on Strings, Regular Expressions and Files and Blobs.

<textarea> or contenteditable?

There are two ways to make editable text on a page.

  • A <textarea> holds plain text in its value. Undo and redo, spell checking, selection APIs and mobile keyboards all work with no extra code. This is the right choice for a plain-text editor.
  • A contenteditable element lets people edit real HTML (bold, links, lists). It is far harder to get right: browsers produce different markup, pasting brings in unwanted styles and you must sanitize the result before saving it. Choose it only when you need rich text, and consider a library.

This project uses a <textarea>. If you later want rich text, the counting functions you write here still work: read element.innerText instead of textarea.value.

Step 1: Count words, characters and reading time

Counting looks easy until you try it. The rules we will use:

  • A word is a run of non-whitespace characters, so \S+ matches words, and an empty or all-space text has zero.
  • Characters are counted twice: with spaces and without. Use [...text].length (or Array.from) so an emoji counts as one character, not two UTF-16 units.
  • Sentences end with ., ! or ?.
  • Reading time assumes about 200 words per minute, rounded up, with a minimum of 1 minute for any non-empty text.
JS Step 1: The counting functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The u flag with \p{L} (any letter) makes topWords work for accented and non-Latin text too.

Step 2: The editor with a live status line

Listen to the input event on the textarea. It fires on every change, including paste, cut, drag-and-drop and undo, so you never need to listen to keyup for this. Update the status text with textContent, and wrap it in an element with role="status" so a screen reader can announce changes politely. Announcing every keystroke can be noisy, so in a production editor you would update that line after a short pause (debounce) instead of on every key.

Number formatting uses Intl.NumberFormat so large counts read well for the visitor's language: 1,804 in English, 1.804 in German.

Step 2: Live counters and text tools

Press Tidy spaces, then Title Case: the stats update because the buttons call update() themselves. Setting area.value from code does not fire an input event, which is the classic gotcha in this kind of app. (The trade-off is that assigning value also clears the browser's undo history, so a Clear that cannot be undone is a good reason to confirm first in a real editor.)

Step 3: Find and replace

Find and replace is two inputs and one function. The important details are escaping what the person typed (so that typing a.b does not mean "a, any character, b"), an optional case-sensitive switch and telling the person how many replacements were made.

JS Step 3: Find and replace

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Using a function as the replacement means $&, $1 and similar patterns in the replacement text are not interpreted. The last line shows why that matters.

Step 4: Download the text as a file

To save the text you create a Blob (a chunk of file-like data), make a temporary URL for it with URL.createObjectURL(), click an invisible <a download> link and then release the URL. This works in every modern browser with no server.

The preview in this lesson runs in a sandbox that blocks downloads, so the example below builds the file and shows its size and a preview, and the full download function is shown after it for your own page.

JS Step 4: Building the file

Press Run (or Ctrl + Enter) to see the console output here.

No output.

On your own page, the download itself looks like this:

JavaScript
function download(text, name) {
  const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = name;           // the file name the browser suggests
  document.body.append(link);
  link.click();
  link.remove();
  URL.revokeObjectURL(url);       // free the memory
}

To open a file instead, use an <input type="file" accept=".txt"> and read it with await input.files[0].text().

Autosave your draft. On a real page, store the text in localStorage from the input handler, debounced (wait about 500 ms after the last keystroke), and restore it when the page loads. The Notes App project shows the pattern with a storage wrapper. The lesson sandbox has no storage, so we keep it out of the demos.

Ideas to extend it

  • Sentence and paragraph counts, plus the average word length.
  • A word-frequency panel using topWords().
  • Word limit such as 280: show a counter that turns red past the limit and use aria-invalid on the textarea.
  • Keyboard shortcuts with a keydown listener (for example Ctrl+S calls download() and preventDefault()).
  • Markdown preview next to the editor.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Which event should a live word counter listen to on a textarea?

    input fires after every edit, including paste, cut, drag-and-drop and undo. keyup misses mouse-driven edits and change only fires when the field loses focus.
  2. 2. Why count characters with [...text].length instead of text.length?

    length counts UTF-16 code units, so "πŸŽ‰".length is 2. Spreading a string iterates by code point, giving 1.
  3. 3. You set textarea.value = "new" from code. What happens to your input listener?

    Changing value from script does not dispatch input. Call your update function directly or dispatch the event.
  4. 4. Why escape the search text before building a RegExp for find and replace?

    Without escaping, typing a.b would match axb too and typing ( would throw a syntax error.

Summary

  • Use a <textarea> for plain text and contenteditable only for rich text.
  • Words are \S+ matches; count characters by spreading the string so emoji count once.
  • Listen to input, and remember that script changes to value fire no event.
  • Format numbers with Intl.NumberFormat and put the summary in a role="status" element.
  • Escape user text before building a RegExp, and use a replacer function to keep $ literal.
  • Download with a Blob, URL.createObjectURL() and a temporary <a download>; revoke the URL afterwards.

Next: Project: Loan, BMI, Tip, Age and Percentage Calculators.