Skip to content Skip to sidebar Skip to footer

Jquery - Count Words In Textarea

Well, I have a Javascript function that returns the number of words that I write into a textarea, but for some reasons, I wanted to write it using Jquery. And, although I tried, I

Solution 1:

A working solution :

functioncontar(){
        alert($.trim($('[name="texto"]').val()).split(' ').filter(function(v){return v!==''}).length);
}

The filter(function(v){return v!==''}) part removes empty strings.

http://jsfiddle.net/qhaYH/

Solution 2:

The simplest solution that cross my mind follows:

//functionfunctioncountWords(tx){
  return tx?tx.replace(/ +/g," ").replace(/\w+| $|^ /g,"").length+1:0;
}
//jQuery plugin
$.fn.countWords = function(){
 returncountWords(this.val()) ;
};

Example HTML:

<textareaid="tester"></textarea><p>WordsCount:<spanid="counter">0</span></p>

JS:

$tester = $("#tester");
$tester.keyup(function(e){
  $("#counter").text($tester.countWords());
});

http://jsbin.com/EfukoYIs/3/edit?html,js,output

Edit Finally I changed concept to count only words in proper meaning (no special chars etc.). The code follows:

//functionfunctioncountWords(tx){
  return tx.replace(/\w+/g,"x").replace(/[^x]+/g,"").length;
}

IMO it's much better. http://jsbin.com/EfukoYIs/5/edit?html,js,output

Solution 3:

Get the value of the textarea, and split it on the space character which will give you an array. Then return the length of that array.

Updated for empty string http://jsfiddle.net/ghyDs/1/

<scripttype="text/javascript">functioncontar() {
        var value = $.trim($('[name="texto"]').val()),
            count = value == '' ? 0 : value.split(' ').length;

        $('[name="cuenta"]').val(count);
    }
</script>

Post a Comment for "Jquery - Count Words In Textarea"