Skip to content

Instantly share code, notes, and snippets.

@jlandry
Created September 4, 2018 14:17
Show Gist options
  • Save jlandry/f9d39df5f73b5d0f016d9ab0bf04cf29 to your computer and use it in GitHub Desktop.
Save jlandry/f9d39df5f73b5d0f016d9ab0bf04cf29 to your computer and use it in GitHub Desktop.
jQuery Word Count
jQuery("textarea").bind("change keyup input", function () {
var limitWord = jQuery(this).next("p").attr("style");
var regex = /\s+/gi;
var wordcount = jQuery.trim(jQuery(this).val()).replace(regex, ' ').split(' ').length;
if (wordcount <= limitWord) {
chars = jQuery(this).val().length;
} else {
var trimmed = jQuery(this).val().split(/\s+/, limitWord).join(" ");
jQuery(this).val(trimmed + " ");
wordcount = jQuery.trim(jQuery(this).val()).replace(regex, ' ').split(' ').length;
chars = jQuery(this).val().length;
}
jQuery(this).next("p").html("Word Count: " + wordcount + "/" + limitWord);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment