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 to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay