Berat Şen Berat Şen - 1 year ago 98
Javascript Question

How can I make a textarea with character limit highlighting like Twitter?

Twitter's submit tweet textbox highlights the characters that are over the character limit:

As you can see, the characters that overrun the character limit are highlighted in red. How can I achieve something like this?

Answer Source

You'll find the necessary solution and required code here:

How to insert <em> tag when exceeding 140 limit i.e. going negative?

...and here:

REGEX - Highlight part over 19 chars

Your question appears to be duplicitous.

Note: I didn't have the option to post the above links as a comment (i.e. privilege contingent on reputation).

Here's the code as per Simon Kuang's recommendation (see comments):


<!DOCTYPE html>
<script src=""></script>
<meta charset=utf-8 />
<title>JS Bin</title>
  <h3>Your text here</h3>
   <div contenteditable="true" id="myDiv">edit me
    <h3>Stuff over 19 characters</h3>
  <div id="extra">
    <h3>Sample output</h3>
    <div id="sample">



.highlight {


$(document).ready(function() {
  $('#myDiv').keyup(function() {
    var content = $('#myDiv').html();
    var extra = content.match(/.{19}(.*)/)[1];


    var newContent = content.replace(extra, "<span class='highlight'>" + extra + "</span>");