DEV Community

Umer S
Umer S

Posted on

A simple way to count characters and words in JavaScript (beginner-friendly)

When I started learning web development, I realized something very basic but important: sometimes we need to count characters and words in a text.

For example:

Limiting input fields
Showing live character count in forms
Optimizing text for social media or SEO

So I tried to build a simple solution in JavaScript.

Basic Example

Here’s a simple way to count characters in an input field:

const input = document.getElementById("text");
const count = document.getElementById("count");

input.addEventListener("input", () => {
count.textContent = input.value.length;
});

This will update the character count in real time as the user types.

Counting Words

If you want to count words instead:

const words = input.value.trim().split(/\s+/).length;
Why this matters
This small feature is used in many real-world applications like:

Twitter-style character limits
Blog editors
SEO tools
Quick Tip

While building this, I also tested my text using an online tool to quickly verify counts and formatting:
compteur de caractres

It’s useful when you don’t want to build everything from scratch or just need a quick check.

If you're learning JavaScript, try building your own version of this. It’s a small project but very practical.

Top comments (0)