Search code examples
javascriptinternet-explorer-9firefox3.5

Count number of words in string using JavaScript


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.


Solution

  • You can make a clever use of the replace() method although you are not replacing anything.

    var str = "the very long text you have...";
    
    var counter = 0;
    
    // lets loop through the string and count the words
    str.replace(/(\b+)/g,function (a) {
       // for each word found increase the counter value by 1
       counter++;
    })
    
    alert(counter);
    

    the regex can be improved to exclude html tags for example