in jQuery

Max number of words in textarea using jQuery

Here is a little code snippet to set a maximum of words in a text area element.

This could be turned into a jQuery function or refactored to be better reused, but there is a sample just to get you going.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$('textarea').keyup(function () {
            var wordArray = this.value.split(/[\s\.\?]+/); //Split based on regular expression for spaces
            var maxWords = 5; //max number of words
            var total_words = wordArray.length; //current total of words
            var newString = "";
            //Roll back the textarea value with the words that it had previously before the maximum was reached
            if (total_words > maxWords+1) {
                 for (var i = 0; i < maxWords; i++) {
                    newString += wordArray[i] + " ";
                }
                this.value = newString;
            }

        });