Sgambe33
Sgambe33

Reputation: 1

Javascript simple word counter

I am trying to make a simple word counter for a textarea element in Javascript. So far I have tried many methods but everyone fails in something. I searched the web but I only found solutions that use functions or JS commands and syntax that I still don't know. The goal is to count the words in a textarea that contains a maximum of 140 characters. The text can also be on more than one line so I have to consider the new line symbol. Till now I wrote this:

for (let i = 0; i < text.length; i++) {
          if (text[i]==' ' && (text[i-1]!==' ' && text[i-1]!=='\n')) { 
            wc++;
            
          }
          else if(text[i]=='\n' && text[i-1]!==' '){
            wc++;
          }
        }

It kind of works but it counts only if after the word I press SPACE. Is there any way to start counting from when the user types just one letter? EDIT: I have already tried the .split(" ") method but it doesn't work with the ENTER/RETURN key. My goal is to start counting as soon as the user types a letter.

Upvotes: 0

Views: 93

Answers (2)

Real Quick
Real Quick

Reputation: 2810

Added replace all multiple spaces with single space. Also added check if entered a new line.

document.getElementById("inputField").addEventListener("input", function(e) {
  // Get the input text value
    var text = this.value;

    //replace all multiple spaces with single space
    text = text.replace(/\s\s+/g, " ");
    // Initialize the word counter
    var wc = 0;

    // Loop through the text
    // and count spaces in it 
    for (let i = 0; i < text.length; i++) {
      if (text[i]==' ' && (text[i-1]!==' ' && text[i-1]!=='\n')) { 
        wc++;

      }
      else if(text[i]=='\n' && text[i-1]!==' '){
        wc++;
      }
    }

    // Display it as output
    document.getElementById("show").innerHTML = wc;
})
<textarea id="inputField" rows=10 cols="60">
</textarea>
<br><br>

<p> Word Count:
    <span id="show">0</span>
</p>

Upvotes: 0

iagowp
iagowp

Reputation: 2494

You can use split along with a regex for whitespace

let words = text.split(/\W/);
wc = words.length;

split breaks your string into an array, it creates a new entry to the array everytime it finds the expression you pass to it.

The regex /\W/ gets whitespaces (' ' and '\n')

So this way it would create an array with every word separated, and then you just need to check the length of the array

Upvotes: 2

Related Questions