JavaScript Word Counter

Counting the number of words in a block of text can be tricky. Users tend to create sections of white space that can throw out most scripts that don't take this into consideration.

I have created a tool for #! code that looks at a textarea of a form, and prints the number of words into an input box in the same form. The textarea calls a function called textCounter() every time a key is pressed. Here is the HTML of the form.

<form onsubmit="return false;" action="" id="wordCountCalc">
<textarea name="message1" rows="10" cols="68" onkeydown="textCounter()" onkeyup="textCounter()"></textarea>
<input readonly="readonly" size="15" type="text" name="len" maxlength="10" value="0" />
</form>

The function works by removing any white space from the start of the text. It then removes any tab characters from the text before splitting the text by one or more white space characters.

The first step is to detect what browser the user is viewing the site in due to a discrepancy between how different browsers split a string apart by white space. The following snippet is used to detect browsers.

var sUserAgent = navigator.userAgent;
var isOpera = sUserAgent.indexOf("Opera")>-1;
var isIE = sUserAgent.indexOf("compatible")>1 && sUserAgent.indexOf("MSIE")>1 && !isOpera;

Here is the function that counts the number of characters in the textarea element.

function textCounter(){
 var area = document.getElementById('wordCountCalc');
 var formcontent;
 if(area.message1.value.length != 0){
  var reg;
  reg = /^\s/gi;
  formcontent = area.message1.value.replace(reg,'');  // remove white space at start or string
  reg = /\t+/g;
  formcontent = formcontent.replace(reg,' '); // remove any tab characters
  reg = /\s+/g;
  formcontent = formcontent.split(reg); // split string by spaces
  if ( isIE ) {
   area.len.value = formcontent.length;
  } else {
   if ( area.message1.value.charAt(area.message1.value.length-1)==' ' ||     area.message1.value.charAt(area.message1.value.length-1)=='\n' ) {
    area.len.value = formcontent.length-1;
   } else {
    area.len.value = formcontent.length;
   };
  };
 }else{
  area.len.value = 0;
 };
};

Try it out for yourself on the number of words tool page. It has been tested quite extensively but if you find any issues or bugs then please post a comment.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
5 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.