4

Lets say I have this.

<div id="somediv"> 
hello, my friend&#39;s &amp; dog are good friends!
</div>

I think that $(somediv).text().length is counting the encodings and not the rendered view. I am doing some truncating on a string if it's too long, and because some of the strings (dynamic) could have &amp; (instead of & ), how do I properly count the total text in a div in its rendered view, not encoded view?

dfsq
  • 191,768
  • 25
  • 236
  • 258
james emanon
  • 11,185
  • 11
  • 56
  • 97

2 Answers2

3

length is going to count &amp; and similar characters as a single character. What may be causing the confusing is that you will also get whitespace before and after your string. If you trim it, you'll see that it is correct.

http://jsfiddle.net/u3byj/

$.trim($(somediv).text()).length
James Montagne
  • 77,516
  • 14
  • 110
  • 130
0

You could do the following as an alternative, if no jQuery is available:

innerHTML.replace(/&(#x?[0-9a-f]+|[a-z]+);/gi,"X").length;
andred
  • 1,204
  • 1
  • 17
  • 29