How to count words in a textarea by jquery and ret

2020-08-09 05:05发布

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.

2条回答
劫难
2楼-- · 2020-08-09 05:34
text_area = $('textarea').val();
text_area.length == 0 ? 0 : text_area.trim().split(/\s+\b/).length
查看更多
放我归山
3楼-- · 2020-08-09 05:35

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

查看更多
登录 后发表回答