ORYON100 ORYON100 - 4 months ago 14
Javascript Question

How to use javascript to count words on a page

My task is to count words on my page, and the code I have so far is counting letters instead. I'm all out of ideas. Here is what it looks like:



var profile_values = document.getElementsByClassName('profile-value');
var total_words = 0;
for (i = 0; i < profile_values.length; i++) {
total_words += profile_values[i].innerHTML.split(' ').length;
}
document.getElementById('word-count').innerHTML = total_words;

<div class="profile-value">
<td>
<p>I am a profile value</p>
</td>
</div>

<div id="stats">
<h3>Stats</h3>
<span id="word-count" class="large">0</span>
<br>words found.
</div>




Answer

You want to get rid of the newlines and trim any extraneous spaces by using trim():

var profile_values = document.getElementsByClassName('profile-value');
var total_words = 0;
for (i = 0; i < profile_values.length; i++) {
  total_words += profile_values[i].innerHTML.trim().split(' ').length;
}
document.getElementById('word-count').innerHTML = total_words;
<div class="profile-value">
  <td>
    <p>I am a profile value</p>
  </td>
</div>

<div id="stats">
  <h3>Stats</h3>
  <span id="word-count" class="large">0</span>
  <br>words found.
</div>