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.
The length of a string in JavaScript can be found using the . length property. Since . length is a property it must be called through an instance of a string class.
The length function in Javascript is used to return the length of an object. And since length is a property of an object it can be used on both arrays and strings.
The RegExp \r Metacharacter in JavaScript is used to find the carriage return character (Carriage return means to return to the beginning of the current line without advancing downward). If it is found it returns the position else it returns -1.
Length is not a method, it is a property. It doesn't actually do anything but return the length of an array, a string, or the number of parameters expected by a function.
<div id="foo">↓</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 = "↓↓↓↓";
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;
}
Since there's no solution using jQuery yet:
var str = 'lol&';
alert($('<span />').html(str).text().length); // alerts 4
Uses the same approach like karim79, but it never adds the created element to the document.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With