Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

278
Vistas
How to use jquery to ignore all whitespace to calculate the true total number of text?

I would like to ask, I want to count the number of text in the demo, but ignore all whitespace! At present, I can only ignore the whitespace before and after the text using trim(), but the whitespace between the text will still be counted. I hope this example The value of console.log in console.log should be 13, the number of words, but now the result will become 17. How can I ignore the white space between the words?

$('.demo').each(function(){
  $(this).text((i, t) => t.trim());
  let textlength = $(this).html().length;
  console.log(textlength);
})
.demo{
  white-space:pre;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="demo">
  
lorem  test  demo
  
</p>

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

I think the easiest way to do this is to replace all whitespace with nothing.

Firstly, to figure out what is whitespace and what isn't, we can use a regular expression.

/\s+/g

This means to find any sort of space, globally across the entire string.

Then it's just a matter of calling .replace()

text.replace(/\s/g, '');
about 4 years ago · Juan Pablo Isaza Denunciar

0

 $('.demo').each(function(){
   $(this).text((i, t) => t.trim());
   let textlength = $(this).html().replace(/\s+/g, '').length;
   console.log(textlength);
 })

We can use a regular expression to remove all whitespaces before calculating the length.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can match against all non-whitespace characters. It will produce an array, and you can check its length.

$('.demo').each(function() {
  const re = /[^\s-]/g;
  const match = this.textContent.match(re);
  console.log(match.length);
});
.demo{ white-space:pre; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="demo">
  
lorem  test  demo
  
</p>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda