JSFiddle - React, Tailwind, and code Playground
HTML
<div contenteditable name="txtScript" id="word_count">Enter more words</div>
<br>
Total word count: <span id="display_count">0</span> words. Words left: <span id="word_left"></span>
CSS
#word_count {
background: white;
border: 1px solid black;
width: 300px;
height: 200px;
}
JavaScript
var wordsLimit = 20;
$(document).ready(function() {
$("#word_count").on('keyup', function() {
var words = $(this).text().match(/\S+/g).length;
if (words > wordsLimit) {
// Split the string on first 200 words and rejoin on spaces
var trimmed = $(this).text().split(/\s+/, wordsLimit).join(" ");
// Add a space at the end to keep new typing making new words
$(this).text(trimmed + " ");
}
else {
$('#display_count').text(words);
$('#word_left').text(wordsLimit-words);
}
});
$('#word_count').trigger('keyup');
});