MacBook avec code sur un bureau

jQuery – Word and Character Counter

A small script to count the number of words and/or characters in an input or textarea field

<input id="text" name="text" type="text" />
<span id="count"></span>

We place the script in jQuery’s ready function to make sure the HTML has been fully loaded.

$(document).ready(function() {
   count($("#text"), $("#count"));
   $("#text").keyup(function() {
      count($("#text"), $("#count"));
   });
});

function count(src, dest) {
   var txtVal = src.val();
   var words = txtVal.trim().replace(/\s+/g, ' ').split(' ').length;
   var chars = txtVal.length;
   if (chars === 0) { words = 0; }
   dest.html(words + ' words<br/>' + chars + ' chars');
}