This article will help you create your own javascript/jQuery word count function, which will also calculate word count on adding more text.

The code below can be used to limit the number of words in a text box(e.g Abstract guideline tool) using the simple javascript with a little bit mix of jQuery.

function WordCount() {
       
        var inp = document.getElementById('txtabstract').value;
     
        var regex = /\s+/gi;
        var wordcount = jQuery.trim(inp).replace(regex, ' ').split(' ').length;      
     
        
        $("#labelcount").html(wordcount);
    }

Here is the working example which can help you count the number of words in a textbox using the code below

Text here : <input type="text" id="txtabstract" value="Testing Word Count" />
Count : <label id="labelcount"></label>

and here is the complete Javascript/jQuery code

function WordCount() {
       //Get Text data
        var inp = document.getElementById('txtabstract').value;
     
        var regex = /\s+/gi;

        var wordcount = jQuery.trim(inp).replace(regex, ' ').split(' ').length;      
            
        
        $("#labelcount").html(wordcount);
    }

  $(document).ready(function(){
    //count word on page load
    WordCount();

    //count word on entering text in TextBox
    $("#txtabstract").on('input',function(){
        WordCount();
 
 
    })  
  })

In the above code, we have bind "input" method using txtabstract Id of input type.

Whenever we add new value in textbox, it again calls WordCount() method, which calculates all words seperated by space " ".

Here is the working fiddle: https://jsfiddle.net/Lrhbv6zv/

Using Pure Javascript

You can also use pure Javascript based solution without using Regex.

const textArea = document.getElementById('description');
//add event listener function to call when textarea text changes
textArea.addEventListener('input', () => {
    var textLn =  textArea.value;
    document.getElementById('wordCount').innerHTML='Total words: '+getWordCount(textLn);
});

function getWordCount(str) {
     return str.split(' ')
       .filter(function(n) { return n != '' })
       .length;
}

and HTML

<div>
  <label>Enter Text:</label>
  <br/>  
  <textarea id="description" name="description" rows="10" cols="70"></textarea> 
  <div id="wordCount">Total words: 0</div>
</div>

Fiddle: https://jsfiddle.net/1j7zbf8L/

In the above code, we are added EventListener using Javascript on textarea input.

Which will then call getWordCount JS function to count words in textarea, once we have count, we are updating HTML of 'wordCount' id div.

That's it.

You may also like to read:

Convert seconds to hh:mm:ss using Javascript

How to detect click outside an element (or div)?