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

6.9k Views Asked by At

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/

6

There are 6 best solutions below

6
Nareen Babu On BEST ANSWER

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>

1
yas17 On

use regex

 function countChars(obj){
    var valLength=obj.value.replace(/\s/g,'').length;
    document.getElementById("charNum").innerHTML = valLength+' 
    characters';}
2
Greg-A On

Did you look good before asking your question?

look at this, it may be able to help you : Show how many characters remaining in a HTML text box using JavaScript

But if you wish to do more simple look below :

html :

<textarea id="field"></textarea>
       <div id="charNum"></div>

javascript:

$("#field").keyup(function(){
  el = $(this);
  if(el.val().length >= 11){
    el.val( el.val().substr(0, 11) );
  } else {
    $("#charNum").text(el.val().length + '/ 10' );
 }

});

0
MrPickles On
function countChars(obj){
    const words = obj.value.split(' ');
    words.length // word count
    console.log('word count is ', words.length)

    const noSpaceString = obj.value.split(' ').join('');
    noSpaceString.length // string length with no space
    console.log('all characters without whits space ', noSpaceString.length)
}
0
Syed Umair Shah Bukhari On
function WordCount() {

    var wordCounterwithSpace = 0;
    var wordCounterwithoutSpace = 0;
    var val = document.getElementById('textAreaId').value;

    for (var i = 0; i < val.length; i++) {
        if (val[i] == ' ') {
            wordCounterwithSpace++;
            continue;
        } else {
            wordCounterwithoutSpace++;
            wordCounterwithSpace++;
        }
    }
    console.log('With Spaces :', wordCounterwithSpace);
    console.log('Without Spaces :', wordCounterwithoutSpace);
}
1
Harsh rana On
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <!DOCTYPE html>
    <html>
      <body style="text-align: center">
        <textarea
          id="txtarea"
          oninput="wordCount()"
          rows="8"
          cols="45"
          placeholder="Enter text ....."
        ></textarea>
        <label>Total Word Count:</label>
        <label id="showCount"></label>

        <script>
          function wordCount() {
            var text = document.getElementById("txtarea").value;
            var count = 0;
            var text = text.replace(/(\r\n|\n|\r)/gm, " ");
            var text = text.replace(
              /[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi,
              ""
            );

            var text = text.replace(/[^a-zA-Z0-9]/g, " ");

            // var text = text.replace(/[^a-zA-Z ]/g, " ");

            var split = text.split(" ");
            for (var i = 0; i < split.length; i++) {
              // text.trim().split(/\s+/).length;
              if (split[i] != "") {
                count++;
              }
            }
            document.getElementById("showCount").innerHTML = count;
          }
        </script>
      </body>
    </html>

    <script></script>
  </body>
</html>