JavaScript Get real length of a string (without entities)

Hedge picture Hedge · Jan 25, 2011 · Viewed 7.9k times · Source

I need to determine the length of string which may contain html-entities.

For example "&darr ;" (↓) would return length 6, which is correct, but I want these entities to be counted as only 1 character.

Answer

karim79 picture karim79 · Jan 25, 2011
<div id="foo">&darr;</div>

alert(document.getElementById("foo").innerHTML.length); // alerts 1

So based on that rationale, create a div, append your mixed up entity ridden string to it, extract the HTML and check the length.

var div = document.createElement("div");
div.innerHTML = "&darr;&darr;&darr;&darr;";
alert(div.innerHTML.length); // alerts 4

Try it here.

You might want to put that in a function for convenience, e.g.:

function realLength(str) { // maybe there's a better name?
    var el = document.createElement("div");
    el.innerHTML = str;
    return el.innerHTML.length;   
}