Home > Mobile >  How to use jquery to ignore all whitespace to calculate the true total number of text?
How to use jquery to ignore all whitespace to calculate the true total number of text?

Time:12-28

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 >
  
lorem  test  demo
  
</p>

CodePudding user response:

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, '');

CodePudding user response:

 $('.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.

CodePudding user response:

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 >
  
lorem  test  demo
  
</p>

CodePudding user response:

You can use string.replaceAll(' ', '') or str.replace(/ /g, '') to remove all spaces in a string. There may still be empty space though, so using trim after replacing is good idea.

$('.demo').each(function(){
  let textTrimmed = $(this).text().replaceAll(' ', '').trim()
  console.log(textTrimmed.length);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p >
  
lorem  test  demo
  
</p>

  • Related