How to Get Word Count using JavaScript

Shiv Yadav Feb 02, 2024
  1. Count Words in a String in JavaScript
  2. Count Words in a String With Regex
How to Get Word Count using JavaScript

We’ll explore how to count words in a paragraph with JavaScript and a couple of real-world examples in this tutorial.

Occasionally, you may need to restrict user input in the text box or limit user input in two ways: the number of characters or words. Today, we’ll look at the latter, namely how to count the number of words in a string using JavaScript.

Count Words in a String in JavaScript

We’ll create a custom JavaScript function that accepts a string input and returns the total number of words in the supplied string. Let’s look at the following example.

Code:

function getWordCount(str) {
  return str.split(' ')
      .filter(function(n) {
        return n != ''
      })
      .length;
}

const sent = 'Hey how are you doing in upwork?';
console.log('Complete Sentence: ' + sent);
console.log('Total words: ' + getWordCount(sent));

Output:

"Complete Sentence: Hey how are you doing in upwork?"
"Total words: 7"

Run Code

First, we split the string on the space character with the broken JavaScript string method, yielding an array of strings. Then we used the filter JavaScript array method to filter out empty strings, which might appear when a series contains two spaces in a row.

Lastly, we have an array of words (along with additional question marks), and we can count the number of elements in the array using the array length property. And that tells us how many words are in a given string.

Count Words in a String With Regex

We learned how to count all words in a string in the previous section by splitting on the space character, and we were able to do this. However, we had to filter out any empty lines that might appear if the original string had many spaces in a row.

We’ll use Regex to revise the previous example in the following code.

Code:

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

const sent = 'Hey how are you doing in upwork?';
console.log('Complete Sentence: ' + sent);
console.log('Total words: ' + getWordCount(sent));

Output:

"Complete Sentence: Hey how are you doing in upwork?"
"Total words: 7"

Run Code

Counting words in a string is significantly more accessible with the split JavaScript string technique. We used the /s+/ regular expression to separate the series into one or more whitespace characters.

In this manner, we can move straight to the desired result without filtering out the empty rows. In addition, the s pattern matches new lines and tabs, resulting in a more robust development than simply checking space characters.

Below is an interactive example to show how to use the get word count function we constructed in the previous areas. Let’s look at the example below, which shows a real-time word counter as the user types in the text box.

Code:

const textArea = document.getElementById('description');
textArea.addEventListener('input', () => {
  var textLn = textArea.value;
  document.getElementById('countText').innerHTML =
      'Total words: ' + getWordCount(textLn);
});

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

Output:

real-time word counter

Live Demo

When a user puts into the text box, a real-time counter appears. If you want to limit the input text, you may utilize and extend this example to display a message to the user.

Author: Shiv Yadav
Shiv Yadav avatar Shiv Yadav avatar

Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.

LinkedIn