Remove whitespace when counting Javascript

Asked

Viewed 1,142 times

2

I have that code:

function contar() {
  var num_caracteres;
  num_caracteres = document.form1.txtTexto.value.length;
  document.getElementById("contador").innerHTML = num_caracteres;
  setTimeout("contar()", 100);
}
<body>
  <form id="form2" name="form1" method="post" action="">
    <label>
      <input type="text" name="txtTexto" id="txtTexto" onkeypress="contar()"/>
      </label>
    <p><label id="contador"></label></p>
  </form>
</body>

How to make it not count the typed blanks?

3 answers

3


Just use .replace(/\s/g,'') of Regex in the value from your Input, so it will remove the blanks. Regex taken out of that question.

function contar(e) {
    var num_caracteres;
    num_caracteres = document.form1.txtTexto.value.replace(/\s/g,'').length;
    document.getElementById("contador").innerHTML = num_caracteres;
    document.getElementById("contadorInput").value = num_caracteres;
    setTimeout("contar()", 100);

}
<body>
  <form id="form2" name="form1" method="post" action="">
    <label>
  <input type="text" name="txtTexto" id="txtTexto" onkeypress="contar(event)"/>
  </label>
    <p>Label: <label id="contador"></label></p>
    
    <p>Input <input type="text"  id="contadorInput" /></p>
    
  </form>
</body>

  • and to display an input instead of the label?

  • @Betinhosilva ready ! example with label and input

1

Before counting the amount, you can remove blank characters with regular expression:

num_caracteres = document.form1.txtTexto.value.replace(/ /g, '').length;

  • and to display an input instead of the label?

  • just select an input type element and assign a value to it: Document.getElementById("element-input"). value = num_characters;

0

Use the replace to remove the spaces:

function contar() {
   var textoSemEspacos = document.form1.txtTexto.value.replace(' ', '');
   var num_caracteres = textoSemEspacos.length;
   document.getElementById("contador").innerHTML = num_caracteres;
   setTimeout("contar()", 100);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.