0

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/

Albert Albs
  • 1
  • 1
  • 3
  • Possible duplicate of [Remove ALL white spaces from text](https://stackoverflow.com/questions/6623231/remove-all-white-spaces-from-text) – User863 Aug 21 '19 at 13:02

6 Answers6

1
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);
}
0

use regex

 function countChars(obj){
    var valLength=obj.value.replace(/\s/g,'').length;
    document.getElementById("charNum").innerHTML = valLength+' 
    characters';}
yas17
  • 401
  • 1
  • 3
  • 14
  • Hi @yas17 Thanks for your answers. Is there anyway I can see the JS code to output both with space between words and without space. **Like Example:** _Total Characters: 300 (With space) 283 (Without Space)_ – Albert Albs Aug 21 '19 at 13:21
0

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' );
 }

});

Greg-A
  • 772
  • 1
  • 19
  • 41
  • Hi @Greg-A Thanks for your answers. However, the code you provided is for counting remaining characters. Since I'm not expert in coding, it is very difficult for me to alter this for counting the total characters. – Albert Albs Aug 21 '19 at 13:18
  • If there are duplicates to be found, please vote to close and indicate the duplicate. Don't replicate existing answers in your own. – isherwood Aug 21 '19 at 13:28
0

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>
Nareen Babu
  • 443
  • 1
  • 5
  • 13
  • Thanks for the quick answer: @user2932057. I checked the code. Actually the "without space" results showing wrong count. Example for the word: `example char count` it says **With space: 18 characters** is correct. but **Without space: 17 characters** is wrong. Actually it is 16 characters without space. _I did not add white-space in the end._ – Albert Albs Aug 21 '19 at 13:31
  • I have modified the code - now its working fine @AlbertAlbs – Nareen Babu Aug 21 '19 at 13:32
  • Awesome. Is there anyway we can count the words as well. Like example: https://easywordcount.com/ – Albert Albs Aug 21 '19 at 13:36
  • @AlbertAlbs I have added words count also in the answer. If you want to implement for other counts like sentences - you need to code it seperately - by using regex. Explore regex for more info – Nareen Babu Aug 21 '19 at 13:50
  • **Awesome.** Thank you so much @user2932057. This is what I expected. And it is working fine. This is best answer for this question. _One update:_ While running this code here on stakeoverflow, and when we empty the textarea field, I'm getting folloing error `{ "message": "Uncaught TypeError: Cannot read property 'length' of null", "filename": "https://stacksnippets.net/js", "lineno": 29, "colno": 37 }` I hope that is related to internal system. – Albert Albs Aug 21 '19 at 18:32
  • @AlbertAlbs - As you stated , when we empty the textarea field => value is null or empty.. Just perform null/empty check before finding out values in count chars methid - it will resolve the problem.. – Nareen Babu Aug 22 '19 at 04:25
0
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)
}
MrPickles
  • 810
  • 1
  • 9
  • 27
0
<!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>

Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36
  • look at this code it may help you,in this code textarea will not contain any special character counting ,new line ,html tags ,tabs etc – Harsh rana Nov 08 '22 at 13:31