How to count a number of words in given string in JavaScript?

Counting words in a JavaScript string requires handling various whitespace scenarios like multiple spaces, leading/trailing spaces, and newlines. Using regular expressions provides an effective solution.

The Challenge

Strings can contain irregular spacing that affects word counting:

  • Leading and trailing spaces
  • Multiple consecutive spaces between words
  • Newlines with spaces
  • Empty strings

Step-by-Step Approach

Step 1: Remove Leading and Trailing Spaces

Use regex to eliminate spaces at the start and end of the string:

str.replace(/(^\s*)|(\s*$)/gi, "");

Step 2: Reduce Multiple Spaces to Single Space

Replace consecutive spaces with a single space:

str.replace(/[ ]{2,}/gi, " ");

Step 3: Handle Newlines with Spaces

Remove spaces after newline characters:

str.replace(/<br> /g, "<br>");

Complete Word Counting Function

<html>
<body>
    <script>
        function countWords(str) {
            // Handle empty or whitespace-only strings
            if (!str || str.trim().length === 0) {
                return 0;
            }
            
            // Remove leading and trailing spaces
            str = str.replace(/(^\s*)|(\s*$)/gi, "");
            
            // Replace multiple spaces with single space
            str = str.replace(/[ ]{2,}/gi, " ");
            
            // Handle newlines with spaces
            str = str.replace(/<br> /g, "<br>");
            
            // Split by space and count
            return str.split(' ').length;
        }
        
        // Test examples
        document.write("Example 1: " + countWords("  Tutorix is one of the best E-learning   platforms") + "<br>");
        document.write("Example 2: " + countWords("Hello    world   JavaScript") + "<br>");
        document.write("Example 3: " + countWords("   ") + "<br>");
        document.write("Example 4: " + countWords("Single"));
    </script>
</body>
</html>
Example 1: 8
Example 2: 3
Example 3: 0
Example 4: 1

Alternative Modern Approach

Using trim() and match() provides a cleaner solution:

<html>
<body>
    <script>
        function countWordsModern(str) {
            if (!str || str.trim().length === 0) {
                return 0;
            }
            
            // Match word sequences (non-whitespace characters)
            const words = str.trim().match(/\S+/g);
            return words ? words.length : 0;
        }
        
        document.write("Modern approach: " + countWordsModern("  Hello   world   JavaScript  "));
    </script>
</body>
</html>
Modern approach: 3

Comparison

Method Handles Empty Strings Code Length Readability
Multi-step Regex With additional check Longer More explicit
trim() + match() Built-in Shorter More concise

Conclusion

Both approaches effectively count words by handling whitespace irregularities. The modern trim() and match() method offers cleaner, more maintainable code for most use cases.

Updated on: 2026-03-15T23:18:59+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements