DEV Community

Cover image for Character Counter with HTML and JS
Walter Nascimento
Walter Nascimento

Posted on

6

Character Counter with HTML and JS

[clique aqui para português]

When we are working with text it is sometimes necessary to know how many characters the text has, or how many words. recently i needed something similar and after using some online tools i thought it would be interesting to create my own character counter, and that is what we are going to do.

CODE

First we will create the interface, we will do something simple, using only HTML.

<h1>Contador de caracteres</h1>

<form name="form_main">
  <fieldset>
    <legend>Contador</legend>
    <label for="text">Texto:</label> <br>
    <textarea name="text" id="text" cols="30" rows="10" oninput="countText()">
    </textarea><br>
    <label for="characters">Caracteres: </label>
    <span id="characters"></span><br>
    <label for="words">Palavras: </label>
    <span id="words"></span><br>
    <label for="rows">Linhas: </label>
    <span id="rows"></span><br>
  </fieldset>
</form>

The HTML structure used oninput, an event that is triggered whenever we have a new data entry.

Now let’s create the countText function.

function countText() {
  let text = document.form_main.text.value;
  document.getElementById('characters').innerText = text.length;
  document.getElementById('words').innerText = text.length == 0 ? 0 : text.split(/\s+/).length;
  document.getElementById('rows').innerText = text.length == 0 ? 0 : text.split(/\n/).length;
}

There, it’s that simple.

Demo

See the complete project working below.

Youtube

If you prefer to watch, I see the development on youtube (video in PT-BR).

Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you! 😊😊

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay