Build a Word Counter Web App: A Step‑by‑Step HTML, CSS, and JavaScript Tutorial

A word counter is a handy tool for writers, students, and developers. In this tutorial, you’ll build a fully functional word counter web app using plain HTML, CSS, and JavaScript. No frameworks needed — just three files and about 30 lines of code.

We’ll create a text area, a button, and a display section. When the user clicks “Count Words”, the app will count words, characters, and sentences. Let’s dive in.

Article illustration

1. Set Up the HTML Structure

Create an index.html file. Add a textarea, a button, and a result div. Use semantic elements for clarity.

  • Add a <textarea> with an ID like textInput.
  • Place a <button> with an onclick that triggers the counting function.
  • Include a <div id="result"> to show the output.

Example HTML snippet

Wrap everything inside a container, and add references to your CSS and JavaScript files. Keep it clean.

2. Style with CSS

In a separate style.css file, center the container, set a font, and style the textarea and button. A minimal design works best:

  • Use max-width: 600px and margin: auto for the container.
  • Add padding and rounded corners to the textarea.
  • Give the button a background color and hover effect for interactivity.

3. Write the JavaScript Logic

Create a script.js file. The core function countWords() does the following:

  • Get the text from the textarea using document.getElementById('textInput').value.
  • Trim the text. If empty, display 0 for all counts.
  • Split the text by whitespace for word count: text.trim().split(/\s+/).filter(w => w).length.
  • Count characters: text.length.
  • Count sentences: split by /[.!?]+/ and filter empty strings.
  • Update the result div with innerHTML.

4. Polish and Test

Handle edge cases (multiple spaces, trailing whitespace). Optionally add real‑time counting using the input event. Test with sample texts.

Your app is ready! Open index.html in a browser and start counting.

Final Code Overview

The entire app uses fewer than 100 lines. The logic is straightforward and easy to extend (e.g., add paragraph count or reading time).

Conclusion

You’ve built a practical word counter web app from scratch. This project reinforces DOM manipulation, string methods, and basic event handling. Customize the design or add features like a “Clear” button. Enjoy coding!

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *