Reputation: 1803
Let's suppose I read the contents of a text node like so:
s = current_node.getSelection().anchorNode.nodeValue;
What is the best way to count how many characters are displayed on the webpage due to this one node? I know that for example
would be displayed as a literal string so no need to look for these. Is all I need to do then to count several spaces in a row as one character? Is there anything else I need to look out for?
Upvotes: 3
Views: 3752
Reputation: 707318
You can ask the browser for the text version of what's in the node like this:
var node = current_node.getSelection().anchorNode;
var text = node.textContent || node.innerText;
var length = text.length;
This will have already converted entities to their regular characters and will not include any HTML tags. Multiple spaces will come out as multiple spaces though - that's just how this function in the browser works. If you were pretty sure that there were no multiple
sequences in the HTML, you could collapse the multiple spaces like this:
var node = current_node.getSelection().anchorNode;
var text = node.textContent || node.innerText;
text = text.replace(/ +/g, " ");
var length = text.length;
Example here: http://jsfiddle.net/jfriend00/FpsGq/
Upvotes: 3
Reputation: 755
It depends on how literally you mean to define "displayed on the webpage". If the characters overflow a container with overflow: hidden, they won't be displayed on the webpage (due to their being hidden by a CSS rule).
Besides that, condensing a series of white spaces, ignoring escaped newlines and carriage returns (if that applies, like in <pre></pre>), and condensing escaped characters should be all you need. I can't think of any other edge cases at least.
Upvotes: 0