2
$(document).ready(function() {

    $("[class^='count[']").each(function() {

        var elClass = $(this).attr('class');
        var minWords = 0;
        var maxWords = 0;
        var countControl = elClass.substring((elClass.indexOf('['))+1, elClass.lastIndexOf(']')).split(',');

        if(countControl.length > 1) {

            minWords = countControl[0];
            maxWords = countControl[1];

        } 

        else { maxWords = countControl[0]; }



        $(this).after('<div class="wordCount"><strong>0</strong> words so far</div>');

            if(minWords > 0) {
                                $(this).siblings('.wordCount').addClass('error');
                             }

        $(this).bind('keyup click blur focus change paste', function() {

            var numWords = jQuery.trim($(this).val()).split(' ').length;
                if($(this).val() === '') {
                        numWords = 0;
                    }

        $(this).siblings('.wordCount').children('strong').text(numWords);
            if(numWords < minWords || (numWords > maxWords && maxWords != 0)) {
                $(this).siblings('.wordCount').addClass('error');
                } 
                else {
                    $(this).siblings('.wordCount').removeClass('error');
                }

        });
    });
});

this script basically counts the spaces between words but if extra spaces are added it counts them as new words too...

http://blog.themeforest.net/tutorials/creating-a-jquery-word-counter/

zadubz
  • 1,281
  • 2
  • 21
  • 36

2 Answers2

9

.split() also accepts regular expressions. Try this:

var numWords = jQuery.trim($(this).val()).split(/\s+/).length;
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
3

Remove all double spaces with a Regex and then do your script. If there are no double spaces to find, it cannot count them.

This is an example in C#, but the same accounts for javascript: How do I replace multiple spaces with a single space in C#?

Community
  • 1
  • 1
Marnix
  • 6,384
  • 4
  • 43
  • 78