DocsHub
JavascriptBeginner

Word Counter

Build a live word counter that counts words as the user types.

Word Counter

Problem

Build a word counter that updates live as the user types inside a textarea. It should count both characters and words at the same time and handle edge cases like extra spaces.

User types: "Hello"
Words: 1   Characters: 5

User types: "Hello World"
Words: 2   Characters: 11

User types: "  Hello   World  "
Words: 2   Characters: 18  — extra spaces do not count as words

User types: ""  (empty)
Words: 0   Characters: 0

Logic

  1. Select the textarea and both display elements
  2. Listen for the input event on the textarea
  3. Read textarea.value to get the full text
  4. Count characters using .length
  5. Count words by splitting on whitespace — filter out empty strings caused by extra spaces
  6. Update both displays on every keystroke

Flow

User types input event fires Read textarea.value Count charactersvalue.length Split by whitespacevalue.trim.split Filter empty strings Count remaining items= word count Update character display Display updated

HTML Structure

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Word Counter</title>
    <style>
      body {
        font-family: sans-serif;
        max-width: 500px;
        margin: 60px auto;
        padding: 0 20px;
      }

      textarea {
        width: 100%;
        height: 180px;
        padding: 12px;
        font-size: 1rem;
        border: 2px solid #ccc;
        border-radius: 8px;
        resize: vertical;
        box-sizing: border-box;
      }

      /* stats row sitting below the textarea */
      .stats {
        display: flex;
        gap: 24px;
        margin-top: 12px;
      }

      .stat {
        font-size: 0.95rem;
        color: #555;
      }

      /* the number part is bigger and darker */
      .stat span {
        font-size: 1.4rem;
        font-weight: 600;
        color: #111;
        display: block;
      }
    </style>
  </head>
  <body>
    <h1>Word Counter</h1>

    <!-- textarea the user types in -->
    <textarea id="text-input" placeholder="Start typing..."></textarea>

    <!-- stats displayed below -->
    <div class="stats">
      <div class="stat">
        <span id="word-count">0</span>
        Words
      </div>
      <div class="stat">
        <span id="char-count">0</span>
        Characters
      </div>
    </div>

    <script src="script.js"></script>
  </body>
</html>

Solution

// Step 1 — select all elements we need
const textarea = document.querySelector("#text-input");
const wordCount = document.querySelector("#word-count");
const charCount = document.querySelector("#char-count");

// Step 2 — listen for input event on the textarea
// fires on every change — typing, deleting, pasting
textarea.addEventListener("input", updateCounts);

function updateCounts() {
  // Step 3 — get the current text from the textarea
  const text = textarea.value;

  // Step 4 — count characters
  // .length counts every character including spaces and newlines
  const characters = text.length;

  // Step 5 — count words
  // .trim() removes leading and trailing spaces first
  // .split(/\s+/) splits on one or more whitespace characters
  // this handles single spaces, multiple spaces, tabs, newlines
  // .filter(Boolean) removes any empty strings from the array
  const words = text.trim() === "" ? 0 : text.trim().split(/\s+/).length;

  // Step 6 — update the display
  wordCount.textContent = words;
  charCount.textContent = characters;
}

Code Execution

Trace through typing "Hello World":

StepCodeResult
Read texttextarea.value"Hello World"
Count chars"Hello World".length11
Trim"Hello World".trim()"Hello World"
Split"Hello World".split(/\s+/)["Hello", "World"]
Count words.length2
Update displaywordCount.textContent = 2Words: 2

Trace through typing " Hello World " (extra spaces):

StepCodeResult
Read texttextarea.value" Hello World "
Count chars.length18
Trim.trim()"Hello World"
Split.split(/\s+/)["Hello", "World"]
Count words.length2

Trace through empty textarea:

StepCodeResult
Read texttextarea.value""
Count chars"".length0
Trim check"".trim() === ""true
Word countreturns 0 directly0

Without the empty check — "".trim().split(/\s+/) returns [""] — an array with one empty string. That would show 1 word on an empty textarea. The text.trim() === "" check catches this and returns 0 directly.


Output

User types "Hello"              → Words: 1   Characters: 5
User types "Hello World"        → Words: 2   Characters: 11
User types "  Hello   World  "  → Words: 2   Characters: 18
Empty textarea                  → Words: 0   Characters: 0

On this page