Search code examples
javascriptjqueryhtmlrich-text-editorword-count

How to get count of word in element 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:

<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.


Solution

  • 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>