Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Get real length of a string (without entities)

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.

like image 597
Hedge Avatar asked Jan 24 '11 23:01

Hedge


People also ask

How do I get the length of a string in JavaScript?

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.

Can you use .length on a string?

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.

What does \r do in JavaScript?

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.

Is string length a function or a property JavaScript?

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.


Video Answer


2 Answers

<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;   
}
like image 136
karim79 Avatar answered Oct 18 '22 15:10

karim79


Since there's no solution using jQuery yet:

var str = 'lol&amp;';
alert($('<span />').html(str).text().length); // alerts 4

Uses the same approach like karim79, but it never adds the created element to the document.

like image 31
ThiefMaster Avatar answered Oct 18 '22 17:10

ThiefMaster