Created
May 11, 2012 15:33
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(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