user4061223
user4061223

Reputation:

How to count the number of words in a Contenteditable div in real time?

<div class="text" id="text" contenteditable="true"></div>

<div class="words"></div>

Whenever the user types into the div 'text', how would I make it so that the number of words entered get displayed into the div 'words'.

I want this to be in real time - no page refreshing.

I,e.

<div class="text" id="text" contenteditable="true">Hello world!</div>

<div class="words">2</div>

Upvotes: 3

Views: 2258

Answers (2)

Josh Crozier
Josh Crozier

Reputation: 240998

You could listen to the input event of the contenteditable element and then split the text and output the length of the array:

  • .trim() removes whitespace at the beginning/end of the string.
  • .replace(/\s+/g, ' ') removes consecutive whitespace so that it isn't counted as an additional word.
  • .split(' ') splits the string at the whitespace so that the count can be retrieved.

As Andreas points out in the comments, you could also split/match the text using word boundaries (/\b/) so that entities like dashes are excluded.

$('#text').on('input', function () {
    var text = this.textContent,
        count = text.trim().replace(/\s+/g, ' ').split(' ').length;
    
    $('.words').text(count);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text" id="text" contenteditable="true">Text</div>
<div class="words"></div>

Without jQuery:

document.getElementById('text').addEventListener('input', function () {
    var text = this.textContent,
        count = text.trim().replace(/\s+/g, ' ').split(' ').length;
    
    document.querySelector('.words').textContent = count;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text" id="text" contenteditable="true">Text</div>
<div class="words"></div>

Upvotes: 4

void
void

Reputation: 36703

This will do it...

$(document).ready(function(){
    $("#text").keyup(function(){

      var text = $(this).text().replace(/\s{2,}/g, ' ');
      var num = text.split(" ").length;
      $(".words").html(text);

    });
});

Upvotes: 0

Related Questions