1

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:

<h1>Hello World</h1> <p> This is Good!!!</p> answer <h2>thanks! </h2>

The javascript should display 7 only.

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

Thanks!

EDIT

What if the sample text is this: <p>11 22&nbsp; 33</p><p>44</p>5<br></div> The javascript should display 5 only.

howardtyler
  • 103
  • 2
  • 12

1 Answers1

2

First you need to get text content of element. You can get text of element using text(). Then you need to remove additional space of text. trim() and replace(/[\s]+/g, " ") remove additional space in text. Now you can convert text to word using split() method.

var length = $(".text").text().trim().replace(/[\s]+/g, " ").split(" ").length;
console.log(length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
    <h1>Hello World</h1> 
    <p> This  is   Good!!!</p> 
    answer 
    <h2>thanks! </h2>
</div>
Mohammad
  • 21,175
  • 15
  • 55
  • 84
  • 2
    adding explanation will help better than providing just the code – guradio Jun 29 '16 at 10:59
  • 1
    But I think it would be a good idea to explain the steps for those who have never used javascript but wish to learn from answers rather than just copy/paste. Example `trim()` will mean nothing to someone new to using javascript, it's not likely someone will just know that `trim()` removes whitespace from both sides of a string or understand what `/[\s]+/` is doing.... – NewToJS Jun 29 '16 at 11:04
  • 1
    Much better with the explanation! Now this can help multiple people who face the same question/problem. +1 for a detailed explanation with reference links to the relevant documentation. – NewToJS Jun 29 '16 at 11:16
  • yes thanks @Mohammad for this with explanation and also to others supporters! :) – howardtyler Jun 29 '16 at 11:28
  • @Mohammad how about if this is the text

    11 22  33

    44

    5
    – howardtyler Jun 29 '16 at 13:10
  • Hi @Mohammad sorry I remove to accept your answer but what if that is the case? thanks – howardtyler Jun 29 '16 at 13:53
  • @howardtyler. No fair changing the question after it's been answered... – Heretic Monkey Jun 29 '16 at 14:00
  • alright will ask the question again thanks @MikeMcCaughan – howardtyler Jun 29 '16 at 14:05