How to Count Words in JavaScript

Today, we will write a program that counts the number of words in a sentence entered by the user.

Example : words counter using Javascript.
<textarea id="my-input"></textarea>
<button onclick="myFunction()">
  Count Words
</button>
<script>
  function myFunction(){
    const myVar = document.querySelector('#my-input').value.split(' ')
    alert("Total Word : "+ myVar.length)
  }
</script>
Try it Yourself »
  1. As you can see, I have created a <textarea> with its id my-input. So that, users can enter some text in it.
    <textarea id="my-input"></textarea>
  2. I have also created a <button> with the onclick attribute and set its value to myFunction(). So that, whenever the button is clicked, myFunction() will be called.
    <button onclick="myFunction()">Count Words</button>
  3. Now it's time to create the myFunction() function. Inside the function, I have select the <textarea> value and split its value into an array of words using the split() method. Stored in a variable named myVar
    <script>
      function myFunction(){
        const myVar = document.querySelector('#my-input').value.split(' ')
      }
    </script>
    The myVar returns an array that represents all the words. For example, if the string is How are you?, then myVar will return the following array.
    🔽Array
     0:"How"
     1:"are"
     2:"you?"
     length:3
      
  4. As you can see in the above example, we got an array. If we target the length property, then we will also get total words.
    function myFunction(){
        const myVar = document.querySelector('#my-input').value.split(' ')
        alert("Total Word : "+ myVar.length)
      }

Conclusion

In this article, I have explained how to count words in Javascript. If you have any queries regarding this topic, then please feel free to comment below.