Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

282
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda