DEV Community

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

Posted on

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! 😊😊

Top comments (0)