Remove whitespace while counting Javascript

2

I have this 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>

    
asked by anonymous 15.08.2017 / 16:11

3 answers

2

Just use .replace(/\s/g,'') of Regex in% w /% of your Input, so it will remove the whitespace. Regex removed from this 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>
    
15.08.2017 / 16:33
1

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

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

    
15.08.2017 / 16:27
0

Use replace to remove spaces:

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