JavaScript

Word Count Using JavaScript

Sometimes, as a JavaScript developer, you must restrict user input into the text box by the character limit or the word limit. In such situations, the counter can help in keeping track of the words or characters when the user enters them. More specifically, the word counter can be utilized to count the words in JavaScript using different approaches.

This write-up will explain the method for counting the words in JavaScript.

How to Count Word Using JavaScript?

As we know, the words in a sentence are separated by a space. This states that the space can be utilized as a separator to count the words in a sentence or string. To count the words in a text area, use the JavaScript predefined methods and properties, including “split()”, “filter()”, and “trim()” methods with regex or without regex.

Example 1: Count Word Using split() and filter() Methods

Firstly, initialize a string surrounded by inverted comma and store it in a variable named “string”:

var string = 'LinuxHint is the best Website for learning skills';

 
Then, print the string using “console.log()” method:

console.log(string);

 
Get the count of words by calling the defined function named “getCount()”:

console.log('Total Words in String: '+ getCount(string));

 
In “getCount()” function, invoke the split() and filter() methods that will split the string based on the spaces, counts the words, and returns the total count:

function getCount(str) {
 return str.split(' ').filter(function(num) {
  return num != ''
 }).length;
}

 
The output displayed the word count of the initialized string as “8” words:


Example 2: Count Word Using trim() and split() Methods

In this example, we will use another approach to perform the same operation. To do so, consider the same string and call “trim()” with the “split()” method, use the regex for space as “/\s+/”, and lastly invoke the “length” property:

function getCount(str) {
 return str.trim().split(/\s+/).length;
}

 
Output


Example 3: Count Words Entered by User in Text Box

In this example, we will count the words in a sentence by entering text in a text box. To do so, create a textbox using the HTML <textarea> tag with id “txtarea” and attach an “onclick()” event to it which invokes the JavaScript user-defined function “wordCount()” to count every word except the spaces:

<textarea id="txtarea" oninput="wordCount()" rows="8" cols="45" placeholder="Enter text ....."></textarea>

 
Then, create two labels; one for description and the other to display the word count:

<label>Total Word Count:</label>
<label id="showCount"></label>

 
In the wordCount() function, first get the id of the text box using the “getElementById()” method, set count equals to 0, and call the split() method by passing space as an argument. Then, iterate the text in the text area using the “for” loop and check if the text does not contain any space, then increment 1 in the count:

function wordCount() {
 var text = document.getElementById("txtarea").value;
 var count = 0;
 var split = text.split(' ');
 for (var i = 0; i < split.length; i++) {
  if (split[i] != "") {
   count ++;
  }
 }
 document.getElementById("showCount").innerHTML = count;
}

 
The output signifies that the word counter works simultaneously when the user enter any text:


We have compiled all the simplest solutions to count the words in JavaScript.

Conclusion

To count the words in a text area, you can utilize the JavaScript predefined methods and properties, including the “split()” method, “filter()” method, and “trim()” method with regex or without regex and “length” property. The word count is mainly used in the forms while entering information in a specific limit. In this write-up, we have explained different methods for counting words in JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.