Count the words in a string in JavaScript
Beginner · 3 min read
Word counts appear everywhere text is written: essay limits, tweet-style boxes, reading-time estimates on blogs, and the little counter under a form field. Counting words sounds like one line of code. That one line gives the wrong answer for an empty box, and for anyone who types two spaces.
In this tutorial you will write countWords(text), which handles leading spaces, double spaces, newlines and empty text. Then you will write a second version, countWordsRegex, with a regular expression. You need to know what a string, an array and a function are.
What counts as a word
For this exercise, a word is any run of characters that aren't whitespace. Whitespace means spaces, tabs and newlines. So 'one two' has two words, ' padded ' has one, and '' (empty text) has none.
Three string tools
split cuts a string into an array at a separator. trim removes whitespace from both ends. length counts the items in an array:
console.log('one two three'.split(' ')); // [ 'one', 'two', 'three' ]
console.log(' padded '.trim()); // padded
console.log(['a', 'b'].length); // 2
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
41 Count words in a sentence
easyCount the words in a piece of text. Decide what happens with leading spaces, double spaces and an empty string.
Stuck? Three hints, smallest first
- 1.
''.split(' ')gives[''], length 1. An empty string has no words. - 2. Trim first, then split on
/\s+/, then handle the empty case explicitly. - 3. A regex
match(/\S+/g)avoids the empty-string problem entirely, but returnsnull.
Step 1: the naive version
Split on a space and count the pieces:
const naive = (text) => text.split(' ').length;
console.log(naive('one two three')); // 3
Correct. Now try the cases real people produce:
const naive = (text) => text.split(' ').length;
console.log(naive('')); // 1
console.log(naive('a b')); // 3
console.log(naive(' hi ')); // 3
An empty box claims one word. Here is why:
console.log(''.split(' ')); // [ '' ]
console.log('a b'.split(' ')); // [ 'a', '', 'b' ]
split always returns at least one piece, even if that piece is empty. And between two spaces there is nothing, so it records an empty string there. Those empty pieces get counted as words.
Step 2: trim, then split on any whitespace
Two changes fix most of this. trim() removes the spaces at the ends, so there are no empty pieces at the start or end. And splitting on the pattern /\s+/ instead of ' ' treats any run of whitespace as one gap. \s means any whitespace character, and + means "one or more in a row".
const count = (text) => text.trim().split(/\s+/).length;
console.log(count(' padded ')); // 1
console.log(count('double spaces here')); // 3
console.log(count('a\nb\tc')); // 3
console.log(count('')); // 1
Padding, double spaces and newlines are all right now. The empty text still says 1, because ''.split(/\s+/) is still [''].
Step 3: handle empty text on purpose
After trimming, text with no words is exactly ''. Check for that first and return 0:
function countWords(text) {
const trimmed = text.trim();
if (trimmed === '') return 0;
return trimmed.split(/\s+/).length;
}
console.log(countWords('one two three')); // 3
console.log(countWords('')); // 0
console.log(countWords(' ')); // 0
console.log(countWords('one')); // 1
Whitespace-only text trims down to '' too, so it also gives 0.
Step 4: count with match instead
There is another way to look at it. Instead of cutting at the gaps, find the words directly. The pattern /\S+/g matches every run of non-whitespace characters (capital \S is the opposite of \s), and the g flag means "find all of them". match returns an array of every match:
console.log('one two three'.match(/\S+/g)); // [ 'one', 'two', 'three' ]
console.log(''.match(/\S+/g)); // null
No empty pieces can appear, because an empty string doesn't match \S+. But notice the second line. When there are no matches, match returns null, not an empty array, and null.length would crash. The ?? operator, "use the right side if the left is null or undefined", swaps in an empty array:
const countWordsRegex = (text) => (text.match(/\S+/g) ?? []).length;
console.log(countWordsRegex(' padded ')); // 1
console.log(countWordsRegex('a\nb\tc')); // 3
console.log(countWordsRegex('')); // 0
Both versions agree on every case. Pick whichever reads more clearly to you.
The full solution
The complete answer has countWords, countWordsRegex and the naive version. It prints the count for five sample texts, shows the naive version miscounting, and checks that the two good versions agree on every sample. Press Run to see the output.
function countWords(text) {
const trimmed = text.trim();
if (trimmed === '') return 0; // the case split() gets wrong
return trimmed.split(/\s+/).length;
}
// The regex route. No empty-string special case, but match returns null.
const countWordsRegex = (text) => (text.match(/\S+/g) ?? []).length;
// The naive version, so the failures are visible.
const naive = (text) => text.split(' ').length;
const samples = ['one two three', ' padded ', 'double spaces here', '', 'one'];
for (const s of samples) {
console.log(JSON.stringify(s).padEnd(24), countWords(s));
}
console.log('naive on "":', naive(''), '<- claims one word');
console.log('naive on "a b":', naive('a b'), '<- claims three');
Output
10 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('three words', countWords('one two three'), 3);
test('padding ignored', countWords(' padded '), 1);
test('double spaces do not add words', countWords('double spaces here'), 3);
test('empty text has no words', countWords(''), 0);
test('whitespace only has no words', countWords(' '), 0);
test('one word', countWords('one'), 1);
test('newlines count as separators', countWords('a\nb\tc'), 3);
test('the naive version miscounts empty text', naive(''), 1);
test('and double spaces', naive('a b'), 3);
test('the regex version agrees everywhere', samples.every((s) => countWords(s) === countWordsRegex(s)), true);
''.split(' ') returning [''] is the trap, and it means the obvious one-liner reports one word for an empty box. Trimming plus an explicit zero case fixes it; so does match(/\S+/g), provided you remember it hands back null rather than an empty array.
Common mistakes
- Splitting on
' '. Double spaces and padding add empty "words", and tabs and newlines don't split at all. - Forgetting the empty case.
''.split(...)returns[''], so an empty box reports one word. - Calling
.lengthstraight onmatch. With no matches it returnsnull, andnull.lengththrows. Add?? [].
Try it yourself
- Show "1 word" or "3 words" under a text box, with the right plural.
- Estimate reading time in minutes at 200 words per minute, rounded up with
Math.ceil. - Write
limitWords(text, max)that returns only the firstmaxwords, joined by single spaces.