0
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.

Dexpras
  • 426
  • 4
  • 11

2 Answers2

1

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

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • 1
    Why is this an improvement? "Try this" explains nothing. – cookie monster Apr 17 '14 at 12:56
  • 1
    @Dexpras is already splitting on spaces, however his version is better than yours because it trims and gets rid of adjacent spaces – cookie monster Apr 17 '14 at 13:00
  • @Dexpras: How did this answer your question? It's a less accurate version of what you're already doing. – cookie monster Apr 17 '14 at 13:07
  • @cookiemonster The different is this return words.length instead of return words. Thats what just I needed to know. – Dexpras Apr 17 '14 at 13:13
  • @Dexpras: In your version, `words` *is* the `length`. No difference. He's just storing the words in the `words` variable and returning `words.length`, while you're storing the `.length` of the words in the `words` variable and returning it. – cookie monster Apr 17 '14 at 13:14
  • 1
    @cookiemonster Yes, But the thing is it did not work that way. – Dexpras Apr 17 '14 at 13:15
  • 1
    @Dexpras: Yes, it does work. I copied your exact code into a demo, and posted it in a comment below your question. This answer is a worse version of your original code. I have no idea why people upvoted it. – cookie monster Apr 17 '14 at 13:16
  • 1
    This will not work accurate for many cases like leading spaces, trailing spaces, more than one space between two words. – PythonDev Apr 18 '14 at 06:38
0
text_area = $('textarea').val();
text_area.length == 0 ? 0 : text_area.trim().split(/\s+\b/).length
MayankS
  • 446
  • 1
  • 3
  • 17