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

Asked

Viewed 2,701 times

5

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

  1. Most obvious: remove tags. I need to locate them, and create a new string without them. It seems to me the slowest and, if the text is large, it may require some memory.

  2. Go through the string: I stop the count every time a tag is opened, and restart when it is closed. It attracts me for the simplicity, but a bit primitive, maybe it slows down in large strings.

  3. Transform into XML and traverse by summing the length of the text nodes. I don’t have much practice, but it seems interesting because it will use the "core" of Javascript, maybe it will be faster and optimize the use of memory accordingly.

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

  • Can you use jQuery or pure javascript only? Could you show an example of this formatted text?

1 answer

7


The solution is much simpler than you think. You don’t need to delete 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>

  • 1

    +1 for the simplicity.

  • Jeez! I didn’t know there was such a miraculous little method! Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.