DEV Community

loading...
Cover image for How To Count The Number Of Words Of A Field In JavaScript

How To Count The Number Of Words Of A Field In JavaScript

elijahtrillionz profile image Elijah Trillionz ・3 min read

To calculate the number of words of an HTML input field, we, first of all, make an event listener of input, to monitor the input field whenever input is made.

const textArea = document.querySelector('textarea'); // textarea or input
textArea.addEventListener('input', calculateWords);
Enter fullscreen mode Exit fullscreen mode

The calculateWords() function is the function we will use to calculate the words. Now calculating the words can be done in one or more ways. We will give just two.

Case One:

function calculateWords(e) {
  return e.target.value.split(' ').length;
}
Enter fullscreen mode Exit fullscreen mode

Yes! that's it, we simply split the value of the input field into an array by a space and calculate the total length of the array. In other words, the last word is added to the array when there is a space after it. Which yes! is not efficient as of now, i.e

What if I just keep hitting the space button?
As of that, the array will keep increasing and the values in the array will be empty (""). Is there a solution, definitely yes!. Why one may think it is not possible to solve this issue with this approach, is because to actually convert a string to an array, you need to split it by something, could be a hyphen (-), a period (.), space (' '), etc.

As you know words are separated by spaces, so we would go for spaces right? yeah!. But what about if I say that the array should not include any empty value (blank spaces). Here is the solution:

function calculateWords(e) {
  const splitArr = e.target.value.split(' ');
  const newSplitArr = splitArr.filter((value) => {
    return value; // returning values with content
  });
  console.log(newSplitArr);
}
Enter fullscreen mode Exit fullscreen mode

There you go, problem solved.

Another issue one may encounter is when the user clears up the values in the field, as such the total length returned by the array will be one (when the input field is empty), but with the above filtering, that has been solved.

Before we made use of the filter() method, the number of words will increase by one when you click the space button. In other words the first calculateWords() function determines a word by a space, but the new one determines a word at the beginning of that word. Try testing the two, to see the difference

Now there was a question, someone asked me would it work with a browser's autocomplete?
Emphatically yes! The autocomplete may have up to 10 or fewer words together, and at once inputs it in the field. But because our event listener is oninput in other words it watches every input that comes into the field, be it autocomplete, pasting, or whatever; as long as an input was made, our calculateWords() function will gladly calculate the number of words.

Case Two:

Regular Expression

function calculateWords(e) {
  return e.target.value.match(/\S+/g).length;
}
Enter fullscreen mode Exit fullscreen mode

Though I am not too good at regular expression, so someone suggested this to me as an alternative, and when I tested it, it worked perfectly well except that whenever the field is completely cleared, it returns an error. The error is as a result of the match() method being null (because the field is empty), and therefore the length of null returns an error. Already you will agree with me that the solution is simple and thus

function calculateWords(e) {
  const fieldValue = e.target.value;
  let numOfWords;
  fieldValue
    ? (numOfWords = fieldValue.match(/\S+/g).length)
    : (numOfWords = 0);
  console.log(numOfWords);
}
Enter fullscreen mode Exit fullscreen mode

There you have it, try testing the two cases and see. The two works 100%.

Discussion (0)

pic
Editor guide