Count characters in paragraph using jQuery (*not* for input/textarea)

前端 未结 4 1876
花落未央
花落未央 2021-01-18 00:55

How do I work out in jQuery a character counter of a p/div tag?

Basically i want to show a different css value IF the character value >=50.

Been struggling f

4条回答
  •  忘掉有多难
    2021-01-18 01:25

    Try this snippet it works even if the text's length was greater than 50 characters.

    You can also calculate the character digits of the paragraph. (Excluding new lines and space bars)

    window.setInterval(function() {
      var txt = $("#txt").val();
      var parLength = $("#data").text().length;
      var charLength = txt.replace(/ /g, '').replace(/\n/g, '').length;
      $("#data").text(txt);
      $("#calcLength").text("The paragrapgh's length is: " + parLength);
      $("#calcChar").text("The amount of characters is: " + charLength);
    }, 10);
    
    
    

    Note: even a space character is calculated through the length function

    Note: a space bar,and every empty line is trimmed in the second calculated value

    I have provided this example to make it simple for use and compatability.

提交回复
热议问题