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.

  3. #3 by Neill Horsman - March 2nd, 2011 at 12:50

    Built up a quick jquery word count down that may help others

    JS:
    $(document).ready(function() {
    $(‘#comment’).keypress(function() {
    var comment = $(‘#comment’).val().split(‘ ‘).length;
    $(‘.value’).html(25 – comment);
    });
    });

    html

    25 Word Remaining

  4. #4 by Zerovic - September 27th, 2011 at 19:33

    what an awesome thing! Thanks for posting! However, it looked a bit complicated on the first try. Couldn’t make it work until I changed all those ’ and ” “ characters to ‘ and ”

    I’m on to it more fancy, with adding colors to it..
    if number of words 95 but < 105 make it green
    else make it red :)

(will not be published)

 


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