JavaScript Program to Count the Number of Words in a String

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

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

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare