Counting and limiting words in a textarea

前端 未结 6 1704
情歌与酒
情歌与酒 2020-11-28 13:35

I managed to make this little jquery function to count the number of words entered in textarea field.

here is the fiddle

and here is the code:

JQUERY

6条回答
  •  清酒与你
    2020-11-28 14:21

    You can use positive lookahead regexes to preserve the whitespace - so that returncodes and tabs are not collapsed to a single space. Something like this:

      var wordLimit = 5;
      var words = 0;
      var jqContainer = $(".my-container");
      var jqElt = $(".my-textarea");
    
    function charLimit()
    {
      var words = 0;
      var wordmatch = jqElt.val().match(/[^\s]+\s+/g);
      words = wordmatch?wordmatch.length:0;
    
      if (words > wordLimit) {
          var trimmed = jqElt.val().split(/(?=[^\s]\s+)/, wordLimit).join("");
          var lastChar = jqElt.val()[trimmed.length];
          jqElt.val(trimmed + lastChar);
      }
      $('.word-count', jqContainer).text(words);
      $('.words-left', jqContainer).text(Math.max(wordLimit-words, 0));
     }
     
     jqElt.on("keyup", charLimit);
     charLimit();
    
    
    words left

提交回复
热议问题