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) {
        $('#wordCount').html(0);
        $('#totalChars').html(0);
        $('#charCount').html(0);
        $('#charCountNoSpace').html(0);
        return;
    }

    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;

    $('#wordCount').html(wordCount);
    $('#totalChars').html(totalChars);
    $('#charCount').html(charCount);
    $('#charCountNoSpace').html(charCountNoSpace);
};

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

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() {    
    $('#text').change(counter);
    $('#text').keydown(counter);
    $('#text').keypress(counter);
    $('#text').keyup(counter);
    $('#text').blur(counter);
    $('#text').focus(counter);
});

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...