Let’s have a quick look at the following example.
As you can see, we’ve made the
Let’s understand how it works. Firstly, we’ve used the
Next, we’ve used the
Finally, we have an array of words (along with other punctuation marks), and we can use the array
length property to count the number of elements in the array. And that gives us the total number of words in a given string!
In this section, we’ll revise that aforementioned example with regex. Let’s have a quick look at the following example.
This time, we split the string with the
/\s+/ regular expression, meaning one or more whitespace characters. This way, we go directly to the result we want, without needing to filter the empty strings. Also, the
\s pattern matches new lines and tabs, making the result more robust than matching space characters directly. As you can see, with the help of the
A Real-World Example
In this section, we'll see a real-world example to demonstrate the use of the
getWordCount function that we built in the previous sections.
Let's go through the following example, which displays a real-time word counter when a user types in the text area.
So, as you can see, when a user types into the text area, it displays a real-time counter! You can use and extend this example to display a message to the user when you want to limit the input text.