JavaScript: how to count the characters of an html text?

5

The problem: I have a html formatted text and I need to count how many characters (ringtones for journalists) I have. I'll use JavaScript. Some solutions came to mind, but as this will be done repetitively, I decided to analyze better before leaving coding:

  • The most obvious: remove the tags. I need to find them, and create a new string without them. It seems to be slower and if the text is large it may require some memory.

  • Scroll through the string: I stop the count every time a tag is opened, and restart when it is closed. It appeals to me for simplicity, but rather primitive, perhaps slow in large strings.

  • Transform into an XML and traverse by adding the lengths of text nodes. I do not have a lot of practice, but it seems interesting because it will use the JavaScript core, maybe get faster and optimize memory usage accordingly.

  • Has anyone ever done anything like this? What is the best "approach" to the problem?

        
    asked by anonymous 09.03.2015 / 15:22

    1 answer

    7

    The solution is much simpler than you are thinking. You do not need to delete the tags, just take their text with the property textContent :

    var elemento = document.querySelector('div');
    // compatibilidade com IE antigo via innerText
    var conteudo = elemento.textContent || elemento.innerText; 
    alert(conteudo.length); // 1
    <div><span>a</span></div>
        
    09.03.2015 / 15:32