Counting Characters and Words

Today, I learned how to create a counting character application. I have seen this on many websites including x.com. The interesting challenge here was not just to count the # of characters that a user is typing. But also to count the number of words. This was done by using the split method.


You have typed 0 characters


You have typed 0 characters and 0 words.

            
                //Get the elements
                let textDisplay = document.querySelector('#textDisplay');
                let characterCount = document.querySelector('#characterCount');
                let wordCount = document.querySelector('#wordCount');
          
                //Use the input method to listen for changes in the text variable
                textDisplay.addEventListener('input', function () {
                  // Gets the word count
                  let words = textDisplay.value.split(/[\s]+/g).filter(function (num) {
                    return num.length;
                  });
          
                  // Display the word count
                  wordCount.textContent = words.length;
          
                  //Display the characters count
                  characterCount.textContent = textDisplay.value.length;
                });
            
          

File Info

Category HTML / JS / CSS
Credits Chris Ferdinandi
Date February 7th, 2025
Codepen NA