JavaScript Program to Count the Number of Words in a String

Introduction

Counting the number of words in a string is a common task in text processing. In most cases, words are separated by spaces, and a word is defined as a sequence of characters separated by one or more spaces. This program demonstrates how to count the number of words in a string using JavaScript.

Problem Statement

Create a JavaScript program that:

  • Accepts a string.
  • Counts the number of words in the string.
  • Returns and displays the word count.

Example:

  • Input: "Hello world this is JavaScript"

  • Output: 6

  • Input: " Welcome to the world of programming! "

  • Output: 6

Solution Steps

  1. Read the Input String: Provide the string either via user input or directly within the code.
  2. Trim and Split the String: Remove any extra spaces from the start and end, then split the string into words using spaces as delimiters.
  3. Count the Words: Count the number of words in the resulting array.
  4. Display the Result: Print the word count.

JavaScript Program

// JavaScript Program to Count the Number of Words in a String
// Author: https://www.javaguides.net/

function countWords(str) {
    // Step 1: Trim any leading/trailing spaces and split the string by spaces
    let wordsArray = str.trim().split(/\s+/);

    // Step 2: Return the number of words
    return wordsArray.length;
}

// Example input
let inputString = "Hello world this is JavaScript";
let wordCount = countWords(inputString);
console.log(`The number of words in the string is: ${wordCount}`);

Output

The number of words in the string is: 6

Example with Different Input

let inputString = "  Welcome to the world of programming!  ";
let wordCount = countWords(inputString);
console.log(`The number of words in the string is: ${wordCount}`);

Output:

The number of words in the string is: 6

Explanation

Step 1: Trim and Split the String

  • The trim() method removes any leading or trailing spaces from the string.
  • The split(/\s+/) method splits the string into an array of words using one or more spaces as the delimiter. This accounts for cases where there may be multiple spaces between words.

Step 2: Count the Words

  • The length of the resulting array (wordsArray.length) gives the number of words in the string.

Step 3: Return and Display the Result

  • The function returns the word count, and it is printed using console.log().

Conclusion

This JavaScript program demonstrates how to count the number of words in a string by trimming extra spaces and splitting the string based on spaces. This method ensures that the word count is accurate even when there are multiple spaces between words or extra spaces at the start and end of the string. This solution is versatile and can handle most word-counting tasks in text processing.

Comments