Word count in textarea

I am showing an example for counting words in textarea. Its a very easy example and the most important part is the “countWords()” function. We are just observing the blur, keyup and focus events on textarea and when user write something in textarea the “words available” updates. You can also see its live demo here.

HTML:

<textarea rows=5cols=50id=”wc” name=”wc”>Hello World</textarea><br />
<span id=”status-ws”>100</span> words available

JavaScript:

<script type="text/javascript">
function updateWord(text, status, wordsAllow) {
	$(status).innerHTML = (+ (wordsAllow - countWords(text)));
}
 
function countWords(text) {
	show_word_count = true;
        var fullStr = text + ” “;
	var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
        var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, “”);
        var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
        var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, ” “);
        var splitString = cleanedStr.split(” “);
        var word_count = splitString.length -1;
 
        if (fullStr.length <2) {
    	      return word_count = 0;
        }
 
	return word_count;
}
 
updateWord($(’wc’).value, ’status-ws’, 100);
$(’wc’).observe(blur, function(oEvent){updateWord($(’wc’).value, ’status-ws’, 100);}, false);
$(’wc’).observe(”keyup”, function(oEvent){updateWord($(’wc’).value, ’status-ws’, 100);}, false);
$(’wc’).observe(focus, function(oEvent){updateWord($(’wc’).value, ’status-ws’, 100);}, false);
</script>

Live Demo


, ,


  1. #1 by Antonio - April 24th, 2009 at 11:43

    here is upgrade, to work with non EN chars

    var initial_whitespace_rExp = /^[^\w\W]+/gi;
    var non_alphanumerics_rExp = rExp = /[^\w\W]+/gi;

  2. #2 by Rytis Lukoševičius - January 6th, 2010 at 22:32

    Thank you for the tip. Exactly what I needed with few modifications just to show the word count as the user is typing into textarea.

(will not be published)


Submit Comment
Subscribe to comments feed
  1. No trackbacks yet.