Word Counter In JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Word Counter</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 20px;
    }
    textarea {
      width: 100%;
      height: 120px;
      font-size: 16px;
      padding: 10px;
    }
  </style>
</head>
<body>

  <!-- Textarea where the user types text -->
  <textarea id="textInput" placeholder="Type your text here..."></textarea>

  <!-- Display word count -->
  <p>Word count: <strong id="wordCount">0</strong></p>

  <!-- JavaScript -->
  <script>
    // Get references to HTML elements
    const textArea = document.getElementById("textInput");
    const wordCountDisplay = document.getElementById("wordCount");

    /**
     * Counts words using regular expression
     * @param {string} text - Input text from textarea
     * @returns {number} - Total number of words
     */
    function countWords(text) {
      // Match all complete words using regex
      // \b  -> word boundary
      // \w+ -> one or more word characters (letters, digits, underscore)
      // g   -> global flag (find all matches)
      const words = text.match(/\b\w+\b/g);

      // If matches exist, return their count
      // If no matches, return 0 (null safety)
      return words ? words.length : 0;
    }

    // Listen for input events (typing, deleting, pasting)
    textArea.addEventListener("input", () => {
      // Get current text from textarea
      const text = textArea.value;

      // Count words and update the UI
      wordCountDisplay.textContent = countWords(text);
    });
  </script>

</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *