JavaScript Program to Count Words of a String

Given the string, the task is to count the words of a string using JavaScript. The words are separated by the following characters: space (‘ ‘) or new line (‘\n’) or tab (‘\t’) or a combination of these.

Below are the following approaches through which we can count words in a string using JavaScript:

Table of Content

  • Count Words of a String using trim() and split() Methods in JavaScript
  • Count Words of a String using Regular Expression and match() Methods in JavaScript
  • JavaScript Program to Count Words of a String using for loop
  • Using String.prototype.split() and filter() Methods


Count Words of a String using trim() and split() Methods in JavaScript

In this approach, we will use the trim() method to remove and trail the space, and the split() method to split the string by one or more spaces.

Example:

Javascript
function wordsLen(str) {
    const array = str.trim().split(/\s+/);
    return array.length;
}

const str = "Welcome, to the GeeeksforBeginner";

console.log("Word count:" ,wordsLen(str));

Output
Word count: 4

Count Words of a String using Regular Expression and match() Methods in JavaScript

In this approach, we will use match() method with the regular expression. The JavaScript String match() method is an inbuilt function in JavaScript used to search a string for a match against any regular expression. So match() will return the array which contains all the string which matches any non-whitespace character.

Example:

Javascript
function numberOfWords(str) {
    const words = str.match(/\S+/g);
    if(words.length!==0){
        return words.length;
    }
    else{
        return 0;
    }
}

const str = "Welcome, to the w3wiki";
console.log("Word count:", numberOfWords(str));

Output
Word count: 4

JavaScript Program to Count Words of a String using for loop

In this approach, we will use for loop to iterate over the string .

  • We will make two variable “count” for storing the count of words and “check” for tracking the loop is inside the word or not.
  • Start a for loop to iterate through each character in the input string.
  • Check if the current character is not a space (' ') and check is false. This means a new word is starting.
    • Increment count to count this new word.
    • Set check to true to indicate that the loop is inside a word.
  • If the current character is a space (' '), it indicates the end of a word.
    • Set check to false to indicate that the loop is not inside a word.
  • return the count.

Example:

Javascript
function numberOfWords(str) {
    let count = 0;
    let check = false;

    for (let i = 0; i < str.length; i++) {
        if (str[i] !== ' ' && !check) {
            count++;
            check = true;
        } else if (str[i] === ' ') {
            check = false;
        }
    }

    return count;
}

const str = "Welcome to the w3wiki";
console.log("Word count:", numberOfWords(str));

Output
Word count: 4

Using String.prototype.split() and filter() Methods

In this approach, we utilize the split() method to split the string into an array of words based on whitespace characters (spaces, tabs, newlines). Then, we use the filter() method to remove any empty strings from the resulting array, which might occur if there are consecutive whitespace characters. The length of the filtered array corresponds to the number of words in the string.

JavaScript
function countWords(str) {
    return str.split(/\s+/).filter(word => word !== '').length;
}

const str = "Welcome, to the w3wiki";
console.log("Word count:", countWords(str));

Output
Word count: 4