Open In App

How to make a word count in textarea using JavaScript ?

Last Updated : 15 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Counting words may be useful in scenarios where the user is recommended to enter a certain number of words and the word counter can keep track of the same.

Below are approaches to make a word count in textarea using JavaScript:

Approach 1: Calculating the number of spaces present in the text

This method relies on the number of spaces present in the input string to count the number of words as every word in a sentence is separated by a space. The function countWord() is defined which takes the text present in the textarea and counts the number of spaces present in it. The input text in the text area is selected by using the getElementById() method.

The drawback of this method is that multiple spaces between words would be counted as multiple words, hence it may cause the word count to be unreliable.

Example: In this example, we are using above explained approach.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width,
                   initial-scale=1.0">
    <title>Document</title>
</head>
 
<body style="text-align: center;">
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
 
    <p>
        Type in the textbox and click on
        the button to count the words
    </p>
 
    <textarea id="inputField" rows=10 cols="60">
    </textarea>
    <br><br>
 
    <button onclick="countWords()">
        Count Words
    </button>
    <br><br>
 
    <p> Word Count:
        <span id="show">0</span>
    </p>
 
    <script>
        function countWords() {
 
            // Get the input text value
            let text = document
                .getElementById("inputField").value;
 
            // Initialize the word counter
            let numWords = 0;
 
            // Loop through the text
            // and count spaces in it
            for (let i = 0; i < text.length; i++) {
                let currentCharacter = text[i];
 
                // Check if the character is a space
                if (currentCharacter == " ") {
                    numWords += 1;
                }
            }
 
            // Add 1 to make the count equal to
            // the number of words
            // (count of words = count of spaces + 1)
            numWords += 1;
 
            // Display it as output
            document.getElementById("show")
                .innerHTML = numWords;
        }
    </script>
</body>
 
</html>


Output:

Approach 2: Separating the words based on spaces and then counting the number of words.

In this approach, we improve the drawback of the previous approach by splitting the words on the basis of the space character and then checking that each split is not only a space character. The countWord() function is called every time the user types in something into the text area using the oninput event handler on the text area.

Example: In this example, we are using above explained approach.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
 
<body style="text-align: center;">
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
 
    <p>
        Type in the textbox to
        automatically count the words
    </p>
 
    <textarea id="word" oninput="countWord()"
              rows="10" cols="60">
    </textarea>
    <br><br>
 
    <p> Word Count:
        <span id="show">0</span>
    </p>
 
    <script>
        function countWord() {
 
            // Get the input text value
            let words = document
                .getElementById("word").value;
 
            // Initialize the word counter
            let count = 0;
 
            // Split the words on each
            // space character
            let split = words.split(' ');
 
            // Loop through the words and
            // increase the counter when
            // each split word is not empty
            for (let i = 0; i < split.length; i++) {
                if (split[i] != "") {
                    count += 1;
                }
            }
 
            // Display it as output
            document.getElementById("show")
                .innerHTML = count;
        }
    </script>
</body>
 
</html>


Output:

Approach 3: Count the words starting from the new line

Since the above two approaches were only able to count words when written in continuation giving spaces, but it was not able to count numbers when each word starts with a new line. So this approach will be able to count the words starting from the new line.

Example: In this example, we are using above explained approach.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
    content="width=device-width,
                   initial-scale=1.0">
    <title>Document</title>
</head>
 
<body style="text-align: center">
    <h1 style="color: green">GeeksforGeeks</h1>
 
    <p>
        Type in the textbox to automatically count the words
    </p>
 
    <textarea id="word" rows="10" cols="60"> </textarea>
    <br /><br />
 
    <p>
        Word Count:
        <span id="show">0</span>
    </p>
 
    <script>
        document
            .querySelector("#word")
            .addEventListener("input", function countWord() {
                let res = [];
                let str = this.value
                .replace(/[\t\n\r\.\?\!]/gm, " ").split(" ");
                str.map((s) => {
                    let trimStr = s.trim();
                    if (trimStr.length > 0) {
                        res.push(trimStr);
                    }
                });
                document.querySelector("#show")
                .innerText = res.length;
            });
    </script>
</body>
 
</html>


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads