howardtyler
howardtyler

Reputation: 103

How to make a word count that contains html tags using javascript?

Hi I would like to do a Word Count in my RTE (Rich Text Editor) with javascript can also use with jquery. But it should not count the html tags and repeating white spaces.

Sample Text:

<p>11 22&nbsp; 33</p><p>44</p>5<br></div>

The javascript should display 5 only.

Is there any javascript code for this and that is also fast to calculate the Word Count?

Thanks!

Upvotes: 1

Views: 7863

Answers (4)

Vladu Ionut
Vladu Ionut

Reputation: 8193

  var words = [];
  function getWords(elements) {
    elements.contents().each(function() {
      if ($(this).contents().length > 0) return getWords($(this));
      if ($(this).text()) words = words.concat($(this).text().split(" "));
    })

  }

  getWords($('<div>').html('<p>11 22&nbsp; 33</p><p>44</p>5<br></div>'));
  console.log(words,words.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Pranav C Balan
Pranav C Balan

Reputation: 115232

You can do something tricky by using jQuery by creating an element with the content.

var str = '<p>11 22&nbsp; 33</p><p>44</p>5<br></div>';

var len = 0;
// create a temporary jQuery object with the content
$('<div/>', {
    html: str
  })
  // get al child nodes including text node
  .contents()
  // iterate over the elements
  .each(function() {
    // now get number or words using match and add 
    len += (this.textContent.match(/[\w\d]+/g) || '').length;
  });

console.log(len);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Roxoradev
Roxoradev

Reputation: 893

Try something like this: You get the html in the div then you remove all tags and replace them with spaces. You remove (trim) all left and right spaces and finally you split the string into an array. The length is your answer.

var cont = $("#content").html();
cont = cont.replace(/<[^>]*>/g," ");
cont = cont.replace(/\s+/g, ' ');
cont = cont.trim();
var n = cont.split(" ").length
alert(n);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content">
<p>11 22&nbsp; 33</p><p>44</p>5<br></div>

Upvotes: 15

asehgal17
asehgal17

Reputation: 31

You can use Countable.js for live word counting, although it doesn't ignore HTML tags.

Upvotes: 0

Related Questions