Monthly Archives: October 2013

Word Count Limiter in JavaScript

Character counts for text is easy; word counts get a bit more subjective.  This can be accomplished with a bit of JavaScript/jQuery and a regular expression.

Google for regular expressions like this and you’re likely to find a vast amount of complicated expressions.  Be careful of these unless you have a specific business need for a complicated regular expression.  I found many counted certain punctuation within a word or adjacent to it as a separate word.  I found a great JSFiddle that contains the simplest way to count words – just look for the spaces between characters.

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

The regex variable is a regular expression that looks for spaces, ignores casing, and performs a global search.  Want to verify that?  Test it out in this RegEx tester.  The wordCount variable trims the empty space outside of the string, replaces any internal whitespace with a single space, and then counts the number single spaces.

Now that you have a way to identify words and count them, the next step is to limit the text box to a certain number of words.  Let’s start with a multi-line text box and word counter:

<textarea id="text-input" cols="25" rows="3"></textarea> 
<div class="word-counter">
	Word Count: <label id="count-label">0</label>/10
</div>

Using a bit of jQuery, you can then count the number of words, update the counter, and limit the textarea input to a maximum number of words (in this case 10 words).

var limitWord = 10;
$("#text-input").keyup(function () {
    $this = $(this);
    var regex = /\s+/gi;
    var wordcount = jQuery.trim($this.val()).replace(regex, ' ').split(' ').length;
    if (wordcount <= limitWord) {
        chars = $this.val().length;
    } else {
        var text = $(this).val();
        var new_text = text.substr(0, chars);
        $(this).val(new_text);
        wordcount --;
    }
    $("#count-label").html(wordcount);
});

The result is:

Word Count Limiter

A working sample can be found here, on JSFiddle: http://jsfiddle.net/justinsaraceno/ezZxf/

Tags: Filled Under: Programming Posted on: October 20, 2013