javascriptword-countcharactercount

Count text area characters with space and without white-space using Simple JavaScript


To count the characters typed in textarea, I have a code that can count with space between words. But I want both the functionalities like to count with words with space and without space in Simple JavaScript.

Since I am not a programming expert, I could not try other methods or frameworks. I prefer Native JavaScript code.

Current JavaScript Code to count Characters with Space:

 

    function countChars(obj){
    document.getElementById("charNum").innerHTML = obj.value.length+' 
    characters';

HTML


    <form name="post" method="POST"> 

<textarea name="new" charset="utf-8" onKeyDown="toggleKBMode(event)" value="copyThisContent" id="newInputID" onKeyPress="javascript:convertThis(event)" style="height:255px; Width:100%; margin-top: -17px; line-height: 15px;" placeholder="Write something.."" onkeyup="countChars(this);"></textarea>

<p id="charNum">0 characters</p>

 </form>


Kindly help me to modify the above code for counting characters in textarea with space and without space. If possible I'm expecting Word count functionality as well.

I am expecting functionalities that is already existing in the following websites. https://easywordcount.com or https://wordcounter.net/


Solution

  • Check this below code snippet:

    function countChars() {
      var val = document.getElementById("newInputID").value;
      var withSpace = val.length;
      // Without using regex
      //var withOutSpace = document.getElementById("newInputID").value.split(' ').join('').length;
      //with using Regex
      var withOutSpace = val.replace(/\s+/g, '').length;
      var wordsCount = val.match(/\S+/g).length;
    
      document.getElementById("wordCount").innerHTML = wordsCount + ' words';
      document.getElementById("charNumWithSpace").innerHTML = 'With space: ' + withSpace + '     characters';
      document.getElementById("charNumWithOutSpace").innerHTML = 'Without space: ' + withOutSpace + '     characters';
    }
    <html>
    
    <body>
      <textarea name="new" charset="utf-8" id="newInputID" style="height:100px; Width:100%; line-height: 15px;" placeholder="Write something.." onkeyup="countChars()"></textarea>
    
      <p id="wordCount">0 Words</p>
      <p id="charNumWithSpace">0 characters</p>
      <p id="charNumWithOutSpace">0 characters</p>
    </body>
    
    </html>