DEV Community

Zoya Khan
Zoya Khan

Posted on

HTML Code for Word Counter

<!DOCTYPE html>
<html>
<head>
    <title>Word Counter</title>
    <script>
        function countWords() {
            // Get user input
            var text = document.getElementById("textInput").value;

            // Split text into array of words
            var words = text.split(/\s+/);

            // Count number of words
            var numWords = words.length;

            // Display result to user
            document.getElementById("wordCountResult").innerHTML = "Number of words: " + numWords;
        }
    </script>
</head>
<body>
    <h1>Word Counter</h1>
    <p>Enter text to count the number of words:</p>
    <textarea id="textInput" rows="10" cols="50"></textarea>
    <br><br>
    <input type="button" value="Count Words" onclick="countWords()">
    <br><br>
    <p id="wordCountResult"></p>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

This code is developed by Zoya from ACPL Tracking. See the blog here.

Top comments (1)

Collapse
 
niswongerkamryn profile image
niswongerkamryn

Creating a word counter in HTML involves using JavaScript along with HTML elements and functions to track the number of words entered into a text area or input field. This functionality enables users to input text, and the code counts the number of words dynamically. When users type or modify the text, the JavaScript code counts the words based on spaces or other defined delimiters, updating the count in real-time. For instance, an online tool like contador de palabras online utilizes HTML input elements coupled with JavaScript logic to analyze and display the word count as users type or paste content into the designated area. The HTML code structures the interface, while the JavaScript handles the word counting functionality, enabling a user-friendly tool for counting words in text.