Dexpras
Dexpras

Reputation: 426

How to count words in a textarea by jquery and return that value

function count(){  
  var val   = $.trim($('textarea').val()),  
      words = val.replace(/\s+/gi, ' ').split(' ').length,
      chars = val.length;
  if(!chars)words=0;

 return words;
}

This function always return 0? Please help.

Upvotes: 0

Views: 1103

Answers (2)

MayankS
MayankS

Reputation: 456

text_area = $('textarea').val();
text_area.length == 0 ? 0 : text_area.trim().split(/\s+\b/).length

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

You can split the textarea value on spaces and then get the words length in it. Try this:

var words = $('textarea').val().split(' ');
alert(words.length);//or return words.length;

working Demo

Upvotes: 1

Related Questions