Count number of words in string using JavaScript

V_B picture V_B · Jul 1, 2011 · Viewed 30k times · Source

I am trying to count the number of words in a given string using the following code:

var t = document.getElementById('MSO_ContentTable').textContent;

if (t == undefined) {
  var total = document.getElementById('MSO_ContentTable').innerText;                
} else {
  var total = document.getElementById('MSO_ContentTable').textContent;        
}
countTotal = cword(total);   

function cword(w) {
  var count = 0;
  var words = w.split(" ");
  for (i = 0; i < words.length; i++) {
    // inner loop -- do the count
    if (words[i] != "") {
      count += 1;
    }
  }

  return (count);
}

In that code I am getting data from a div tag and sending it to the cword() function for counting. Though the return value is different in IE and Firefox. Is there any change required in the regular expression? One thing that I show that both browser send same string there is a problem inside the cword() function.

Answer

KooiInc picture KooiInc · Jul 1, 2011

You can use split and add a wordcounter to the String prototype:

if (!String.prototype.countWords) {
  String.prototype.countWords = function() {
    return this.length && this.split(/\s+\b/).length || 0;
  };
}

console.log(`'this string has five words'.countWords() => ${
  'this string has five words'.countWords()}`);
console.log(`'this string has five words ... and counting'.countWords() => ${
  'this string has five words ... and counting'.countWords()}`);
console.log(`''.countWords() => ${''.countWords()}`);