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 :

function contar(){
        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:

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

Example HTML:

<textarea id="tester"></textarea>
<p>WordsCount:<span id="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:

//function
function countWords(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/

<script type="text/javascript">
    function contar() {
        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"