Right now, your
this.value.length > 400
comparison checks the number of characters, and not words (such a check probably makes sense too -- but then the number would be bigger and that's not related to the number of word check). So you have to split up the string in words and compare the length of the array of words:
var words = this.value.split(/\W+/);
if (words.length > max) {
e.preventDefault();
} else if (words.length > max) {
alert("You can only have 400 words.");
return;
}
split
splits a JavaScript string by a separator - this can be a string, or, like in this case, a
regular expression[
^]. Every time the regular expression gets matched, a split is performed.
\W+
is the regular expression here:
\W
means 'non-word' character,
+
means '1 or more'. So this
split
call will split on all (series of) non-word characters. The
+
is necessary because otherwise you'd get empty strings in the word array if someone used multiple non-word characters next to each other.
This is the definition of \W:
Matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_].
For example, /\W/ or /[^A-Za-z0-9_]/ matches "%" in "50%".