Skip to content

Instantly share code, notes, and snippets.

@benpickles
Created May 11, 2012 15:33
Show Gist options
  • Save benpickles/2660478 to your computer and use it in GitHub Desktop.
Save benpickles/2660478 to your computer and use it in GitHub Desktop.
Quick jQuery plugin to count the number of words in an input/textarea.
;(function($) {
var NONBLANK = /\S/
var SPLITTER = /[^a-z0-9-]+/i
function countWords(string) {
var trimmed = string.replace(/^\s+|\s+$/g, "")
if (NONBLANK.test(trimmed)) {
return trimmed.split(SPLITTER).length
} else {
return 0
}
}
$.fn.wordcount = function(callback) {
return this.each(function() {
var input = $(this)
input.on("keyup", function() {
callback.call(this, countWords(input.val()))
})
callback.call(this, countWords(input.val()))
})
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment