JavaScript Word Counter

23rd September 2008

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.

 

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.

  1. var sUserAgent = navigator.userAgent;
  2. var isOpera = sUserAgent.indexOf("Opera")>-1;
  3. 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.

  1. function textCounter(){
  2. var area = document.getElementById('wordCountCalc');
  3. var formcontent;
  4. if(area.message1.value.length != 0){
  5. var reg;
  6. reg = /^\s/gi;
  7. formcontent = area.message1.value.replace(reg,''); // remove white space at start or string
  8. reg = /\t+/g;
  9. formcontent = formcontent.replace(reg,' '); // remove any tab characters
  10. reg = /\s+/g;
  11. formcontent = formcontent.split(reg); // split string by spaces
  12. if ( isIE ) {
  13. area.len.value = formcontent.length;
  14. } else {
  15. if ( area.message1.value.charAt(area.message1.value.length-1)==' ' || area.message1.value.charAt(area.message1.value.length-1)=='\n' ) {
  16. area.len.value = formcontent.length-1;
  17. } else {
  18. area.len.value = formcontent.length;
  19. };
  20. };
  21. }else{
  22. area.len.value = 0;
  23. };
  24. };

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.