Friday, December 23, 2011

JS: Word Count using Javascript

I just made a word counter using Javascript. Started it of as a jsfiddle attempt out of boredom. Thought it will help me count the words in assignments. blah. I have also made the source code available in github.

The counter is a simple javascript function, but have used jQuery selectors for simplicity and easiness. Initially my aim was to just get the count of words in the textarea by splitting the spaces and adding 1. But that approach is not accurate, when there are multiple spaces between words. So I used regular expression for replacing multiple spaces with a single space: /\s+/gi.

counter = function() {
    var value = $('#text').val();

    if (value.length == 0) {

    var regex = /\s+/gi;
    var wordCount = value.trim().replace(regex, ' ').split(' ').length;
    var totalChars = value.length;
    var charCount = value.trim().length;
    var charCountNoSpace = value.replace(regex, '').length;


The results are set in <span> elements as follows:

Now attach the counter function to change, keydown, keypress, keyup, blur and focus events of the textarea, to make sure the function called on every change.

$(document).ready(function() {    

This can be accessed in the following links

1. Word Counter using javascript

2. Source code for word counter using javascript

3. jsFiddle for word counter using javascript

Please report any bugs, issues or suggestions in github or just comment here.

Share it if you liked!
Related Posts Plugin for WordPress, Blogger...