The Wayback Machine - https://web.archive.org/web/20240914131855/https://www.geeksforgeeks.org/how-to-make-a-word-count-in-textarea-using-javascript/
Open In App

How to make a word count in textarea using JavaScript ?

Last Updated : 24 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

im3


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:

im3


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:

im3




Similar Reads

What is the difference between “word-break: break-all” versus “word-wrap: break-word” in CSS ?
The word-break property in CSS is used to specify how a word should be broken or split when reaching the end of a line. The word-wrap property is used to split/break long words and wrap them into the next line. Difference between the "word-break: break-all;" and "word-wrap: break-word;" word-break: break-all; It is used to break the words at any ch
2 min read
How to make sure clients have enough words in textarea by using angularjs in order to disable/enable a button?
The Task here is to make sure that the user enters enough words in the Textarea. The button will be enabled or disabled on the basis of the word count entered by the client or user. Here the word limit will be set by admin of the project or Application. If word count lies between the parameter set by Admin then the button will remain enabled. If wo
4 min read
How to find all textarea and paragraphs to make a border using jQuery ?
Given a set of textareas, the task is to apply a border on each of them and subsequently add some paragraphs and then define a border on every paragraph using the jQuery library. Approach 1: Using the click(), css() and add() methods in jQuery: There are two textareas, two paragraphs, and one button defined in the following example. The button has
3 min read
Javascript Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}Output : "gee"Input : {"apple", "ape", "april"}Output : "ap"We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”. What is the longest common prefix in both of them? It is “geeks”.Now let us introduce
3 min read
How to make textarea 100% without overflow when padding is present?
To ensure a &lt;textarea&gt; fills 100% width without overflow when its parent has padding, use the box-sizing: border-box property. This includes the padding and border in the element's total width, preventing overflow. ApproachMake the basic HTML web page using different elements. The .wrapper class applies padding of 20px and a margin of 15px, g
1 min read
How to change the shape of a textarea using JavaScript ?
In General, Textarea will be in the form of rectangular or square shapes, but here we will deal with Unusual shapes of textarea which means this textarea will not be regular shapes but editable. Method 1: In the first method, let's see the irregular editable textarea created using CSS-shapes and content editable attribute when it is true. Example:
2 min read
How to set textarea scroll bar to bottom as a default using JavaScript/jQuery ?
Given an HTML document containing &lt;textarea&gt; element and the task is to set the position of scrollbar to bottom of &lt;textarea&gt; with the help of jQuery. Approach 1: Get the scrollHeight property of the textarea. Use scrollTop property to set the position of vertical scrollbar using jQuery. Example: This example implements the above approa
3 min read
How to disable arrow key in textarea using JavaScript ?
Given an HTML element containing the &lt;textarea&gt; element and the task is to disable scrolling through arrow keys with the help of JavaScript. Approach 1: Add an event listener onkeydown on the window.If the event happens then check if the keys are arrow or not.If arrow key is pressed then prevent its default behaviour. Example: This example im
2 min read
How to create auto-resize textarea using JavaScript/jQuery ?
Textareas is the area for the input but the input size should be long. We can resize the input area. Create a textarea and the task is to automatically resize it when we type or paste the content in it. It can be achieved by using JavaScript and jQuery: Table of Content Using JavaScriptUsing jQueryMethod 1: Using JavaScriptTo change the height, a n
4 min read
How to change the Content of a textarea using JavaScript ?
To change the content of an &lt;textarea&gt; element with the help of JavaScript, we use DOM manipulation for this with some inbuilt DOM manipulation methods. Methods to change the Content of the text Area: Table of Content JavaScript .value methodJavaScript .innerHTML methodJavaScript textContent methodUsing JavaScript innerText methodsMethod 1: J
3 min read
How to Disable Textarea using JavaScript?
This article will show you how to disable the textarea using JavaScript. Disabling a textarea using JavaScript can be done by setting the disabled property of the textarea element to true. This prevents the user from editing the content of the textarea. There are some reasons to use disabled textarea, these are: Disabling a textarea prevents the us
2 min read
Create a Character Limit Textarea using HTML CSS and JavaScript
In this article, we will create a Character Limit Textarea using HTML, CSS, and JavaScript. In this application, we will display the text area as an input component to the user and there is a predefined limit set to accept the input. When the limit is been crossed the user will get the alert message and he will not be able to type further in the te
6 min read
How to limit character input in textarea including count in jQuery ?
In this article, we will set the limit character input in the textarea including count in the jQuery. To set the limit character in the input textarea, we use length property. Approach: We create an input text area with a given maxlength and then use jQuery code to limit the characters. First, we set the max limit and then use keyup() method to red
1 min read
How to disable resizable property of textarea using CSS?
This resizable property is used to set the resizable area of elements. It is mostly used with textarea and div elements. To disable resizable property of an element use resize to none. It is the default value. Syntax resize: none;Example: C/C++ Code &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Disable resize property&lt;/title&gt;
1 min read
How to create a Textarea Input Box using jQuery Mobile ?
jQuery Mobile is a web based technology used to make responsive content that can be accessed on all smartphones, tablets and desktops. In this article, we will be a Textarea Input box using jQuery Mobile. Approach: Add jQuery Mobile scripts needed for your project. &lt;link rel=”stylesheet” href=”http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.
1 min read
How do you Make an If Statement in JavaScript that Checks if a Variable is Equal to a Certain Word ?
In this article, we will discuss How You Make An If Statement In JavaScript That Checks If A Variable is Equal To A Certain Word. In JavaScript, an if statement is a basic control structure that allows you to conditionally execute code based on specified conditions. A common use case is to check if the value of the variable is equal to a specific w
2 min read
HTML | DOM Textarea autofocus Property
The DOM Textarea autofocus Property is used to set or return whether the element should get focus when the page loads. This property is used to reflect the HTML autofocus attribute. Syntax: It is used to Return the autofocus property. textareaObject.autofocusIt is used to Set the autofocus property. textareaObject.autofocus = true|false Property Va
2 min read
HTML DOM textarea minlength Property
The HTML DOM textarea minlength property is used to set or return the value of the minlength attribute of a textarea field. It specifies the minimum number of characters that have been allowed in the Element. Syntax: It returns the minLength property. textareaObject.minLengthIt is used to set the minLength property. textareaObject.minLength = numbe
2 min read
HTML | DOM Textarea maxlength Property
The DOM Textarea maxlength Property is used to set or return the value of the maxlength attribute of a textarea field. It specifies the maximum number of characters that have been allowed in the Element. Syntax: It is used to return the maxLength property: textareaObject.maxLength It is used to set the maxLength property: textareaObject.maxLength =
2 min read
HTML &lt;textarea&gt; disabled Attribute
The disabled attribute for &lt;textarea&gt; element in HTML is used to specify that the text area element is disabled. A disabled text area is un-clickable and unusable. It is a boolean attribute. Syntax: &lt;textarea disabled&gt;text content...&lt;/textarea&gt; Example: C/C++ Code &amp;lt;!DOCTYPE html&amp;gt; &amp;lt;html&amp;gt; &amp;lt;head
1 min read
HTML DOM Textarea cols Property
The DOM Textarea cols Property is used to set or return the value of the cols attribute of a textarea field. The cols attribute how many average-width characters should fit on a single line. Syntax: It is used to return the cols property.textareaObject.colsIt is used to Set the cols property:textareaObject.cols = number Property Values: number: It
2 min read
HTML DOM Textarea select() Method
The select() method in HTML DOM is used to select the entire content of the text area or in a &lt;input&gt; element that includes a text field. Syntax: textareaObject.select() Parameters: This method does not accept any parameters. Return Value: It does not return any value. Example: In this example, we will see the use of the select() method C/C++
1 min read
HTML | DOM Textarea Object
The Textarea Object in HTML DOM is used to represent the HTML &lt;textarea&gt; Element. The textarea element can be accessed by using getElementById() method.Syntax: document.getElementById("ID"); Where ID is assigned to the &lt;textarea&gt; element.Property Values: autofocus: It is used to set or return whether the element should get focus when th
3 min read
HTML DOM Textarea disabled Property
The DOM Textarea disabled Property is used to set or return whether the textarea element would be disabled or not. A disabled text area is un-clickable and unusable. It is a boolean attribute and is used to reflect the HTML Disabled attribute. Syntax: It is used to return the disabled property.textareaObject.disabledIt is used to set the disabled p
2 min read
HTML | DOM Textarea placeholder Property
The DOM Textarea placeHolder Property is used to set or return the value of the placeholder attribute of a textarea field. It specifies a short hint that describes the expected value of an input field / textarea. A short message or hint displayed before entering value in textarea. Syntax: It is used to Return the placeholder property. textareaObjec
2 min read
HTML | DOM Textarea rows Property
The DOM Textarea rows Property is used to set or return the value of a rows attribute of a textarea field. The rows attribute specifies the number of visible text lines for the control i.e the number of rows to display. Syntax: It is used to Return the rows property:textareaObject.rowsIt is used to Set the rows property:textareaObject.rows = number
2 min read
HTML | DOM Textarea required Property
The DOM Textarea required Property is used to set or return the Whether that the input element must be filled out before submitting the Form. This Property is used to reflect the HTML required attribute.Syntax: It is used to Return the required property: textareaObject.requiredIt is used to Set the required property: textareaObject.required = true|
2 min read
HTML | DOM Textarea wrap Property
The DOM Textarea wrap Property is used to set or return the value of the wrap attribute of the textarea. It describes the way the text to be wrapped while submitting a form. Syntax: It is used to return the wrap property.textareaObject.wrapIt is used to set the wrap property.textareaObject.wrap = soft|hard Property Values: soft: It defines that the
2 min read
HTML | DOM Textarea readOnly Property
The DOM Textarea readOnly Property is used to set or return that the text in the textarea should be readOnly or not. If it is readOnly then the content cannot be modified but it can be copied.Syntax: It is used to return the readOnly property.textareaObject.readOnlyIt is used to set the readOnly property.textareaObject.readOnly = true|false Propert
2 min read
HTML | DOM Textarea name Property
The DOM Textarea name Property is used to set or return the value of the name attribute of a textarea field. Syntax: It is used to return the name property.textareaObject.nameIt is used to set the name property:textareaObject.name = text/value Property Values: text: It specifies the name of the text area. Return Value: It returns the name of the te
2 min read