howardtyler howardtyler - 1 year ago 88
jQuery Question

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?



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.

Answer Source

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;
<script src=""></script>
<div class="text">
    <h1>Hello World</h1> 
    <p> This  is   Good!!!</p> 
    <h2>thanks! </h2>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download