JavaScript Program to Count Words in a String
Use
str.trim().split(/\s+/).length in JavaScript to count words in a string by trimming spaces and splitting by whitespace.Examples
InputHello world
Output2
Input This is a test string.
Output5
Input
Output0
How to Think About It
To count words, first remove extra spaces at the start and end using
trim(). Then split the string by spaces or any whitespace using a regular expression like /\s+/. The number of resulting parts is the word count. If the string is empty or only spaces, the count is zero.Algorithm
1
Get the input string.2
Remove leading and trailing spaces using trim.3
Split the trimmed string by one or more whitespace characters.4
Count the number of parts from the split.5
If the string is empty after trimming, return zero.6
Return the count as the number of words.Code
javascript
function countWords(str) { if (!str.trim()) return 0; return str.trim().split(/\s+/).length; } console.log(countWords('Hello world')); // 2 console.log(countWords(' This is a test string. ')); // 5 console.log(countWords('')); // 0
Output
2
5
0
Dry Run
Let's trace the input ' This is a test string. ' through the code.
1
Input string
' This is a test string. '
2
Trim spaces
'This is a test string.'
3
Split by whitespace
['This', 'is', 'a', 'test', 'string.']
4
Count words
5
| Step | Value |
|---|---|
| Trimmed string | This is a test string. |
| Split array | ['This', 'is', 'a', 'test', 'string.'] |
| Word count | 5 |
Why This Works
Step 1: Trim the string
Using trim() removes spaces at the start and end so they don't count as words.
Step 2: Split by whitespace
Splitting by /\s+/ divides the string into words separated by any spaces or tabs.
Step 3: Count the parts
The length of the split array is the total number of words in the string.
Alternative Approaches
Using match with regex
javascript
function countWords(str) { const words = str.match(/\b\w+\b/g); return words ? words.length : 0; } console.log(countWords('Hello world')); // 2
This method uses regex to find word boundaries and counts matches; it handles punctuation better but may be slower.
Manual loop counting
javascript
function countWords(str) { let count = 0; let inWord = false; for (const char of str) { if (char.trim() !== '') { if (!inWord) { count++; inWord = true; } } else { inWord = false; } } return count; } console.log(countWords('Hello world')); // 2
This approach counts words by checking characters one by one; it's more manual but avoids splitting.
Complexity: O(n) time, O(n) space
Time Complexity
The program scans the string once to trim and split, so time grows linearly with string length.
Space Complexity
Splitting creates an array of words, so space grows with the number of words.
Which Approach is Fastest?
Splitting by whitespace is simple and fast for most cases; regex match is more flexible but slightly slower; manual counting uses less memory but more code.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Split by whitespace | O(n) | O(n) | Simple and fast word count |
| Regex match | O(n) | O(n) | Handles punctuation better |
| Manual loop | O(n) | O(1) | Memory efficient, more control |
Always trim the string before splitting to avoid counting empty words.
Beginners often forget to trim the string, causing extra empty words to be counted.