Count words with regex in JavaScript
Intermediate · 3 min read
Word counts appear everywhere: the counter under a tweet box, the "minimum 50 words" rule on an essay form, the reading time on a blog post. Counting words sounds easy, and the first attempt usually works on tidy text. Then someone types two spaces between words, or starts a line with a space, and the count is wrong.
In this tutorial you will write countWords so it gives the right number for messy text too, and you will meet the two traps that catch almost everyone. You need to know split, length and trim. The regex parts are explained as we go.
Splitting text into pieces
split cuts a string wherever it finds a separator and gives back an array of the pieces. Count the pieces and you have counted the words:
console.log('Lagos to Abuja'.split(' ')); // [ 'Lagos', 'to', 'Abuja' ]
console.log('Lagos to Abuja'.split(' ').length); // 3
Splitting on a pattern
split also accepts a regular expression. \s is any whitespace character (space, tab, new line) and + means "one or more in a row". So /\s+/ treats a whole run of whitespace as a single separator:
console.log('Lagos to\tAbuja'.split(/\s+/)); // [ 'Lagos', 'to', 'Abuja' ]
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
6 Count the words in a string
fairCount words. The question is explicit: trim the ends, collapse runs of two or more spaces into one, and do not let a line starting with a space create an extra word.
Stuck? Three hints, smallest first
- 1. Trim first, then split on
/\s+/, which collapses runs for you. - 2. The empty string is the special case:
‘’.split(/\s+/)gives[‘’], length 1. - 3.
match(/\S+/g)is the other route, and it returnsnullrather than an empty array.
Step 1: the naive version and its bug
Start with what most people write first:
const naive = (text) => text.split(' ').length;
console.log(naive('Lagos to Abuja')); // 3
console.log(naive('Lagos to Abuja')); // 10
Three words, counted as 10. Splitting on a single space means every extra space makes an empty piece:
console.log('a b'.split(' ')); // [ 'a', '', 'b' ]
Step 2: split on runs of whitespace
Swap the single space for /\s+/:
const better = (text) => text.split(/\s+/).length;
console.log(better('Lagos to Abuja')); // 3
console.log(better(' Lagos to Abuja ')); // 5
The runs are fixed, but spaces at the start and end still make an empty piece at each end. That is the "line starting with a space" problem the exercise warns about.
Step 3: trim first
trim() removes the whitespace at both ends before we split, so no empty pieces are left at the edges:
const almost = (text) => text.trim().split(/\s+/).length;
console.log(almost(' Lagos to Abuja ')); // 3
console.log(almost('')); // 1
The empty string has no words, but the count says 1. Why?
console.log(''.split(/\s+/)); // [ '' ]
Splitting an empty string gives an array with one empty string in it, not an empty array.
Step 4: guard the empty case
Check for empty text before splitting. This also covers text that is only spaces, because trim turns it into '':
function countWords(text) {
const trimmed = text.trim();
if (trimmed === '') return 0;
return trimmed.split(/\s+/).length;
}
console.log(countWords(' Lagos to Abuja ')); // 3
console.log(countWords('\n Lagos\n to\n Abuja\n')); // 3
console.log(countWords('')); // 0
console.log(countWords(' ')); // 0
console.log(countWords("it's a bus")); // 3
Hyphens and apostrophes are not whitespace, so one-word and it's each count as one word.
Step 5: the other route, match
Instead of splitting on the gaps, you can count the words themselves. \S (capital S) means "any character that is not whitespace", so /\S+/g finds every run of non-space characters:
const countByMatch = (text) => (text.match(/\S+/g) ?? []).length;
console.log(countByMatch(' Lagos to Abuja ')); // 3
console.log(countByMatch('')); // 0
console.log(''.match(/\S+/g)); // null
match gives back null, not an empty array, when nothing matches. ?? [] swaps that null for an empty array, so .length works and gives 0.
The full solution
The panel has both versions and the naive one side by side, run over messy inputs with extra spaces, new lines and empty text. Press Run and compare the naive count on each line.
// Trim, then split on any run of whitespace. The run does the collapsing.
function countWords(text) {
const trimmed = text.trim();
if (trimmed === '') return 0; // without this you get 1
return trimmed.split(/\s+/).length;
}
// The other way: count the non-whitespace runs. Note match returns null.
const countByMatch = (text) => (text.match(/\S+/g) ?? []).length;
// The bug the question is warning about.
const naive = (text) => text.split(' ').length;
const cases = [
'Lagos to Abuja',
' Lagos to Abuja ',
'Lagos to Abuja',
'\n Lagos\n to\n Abuja\n',
'Lagos',
'',
' ',
'one-word',
"it's a bus",
];
for (const t of cases) {
console.log(JSON.stringify(t).padEnd(30), 'count:', countWords(t), ' naive split(" "):', naive(t));
}
console.log("'' .split(/\\s+/) gives", JSON.stringify(''.split(/\s+/)), 'length', ''.split(/\s+/).length);
console.log("'abc'.match(/xyz/) gives", 'abc'.match(/xyz/), '<- null, not []');
Output
16 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 16 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('Lagos to Abuja'), 3);
test('surrounding spaces do not add words', countWords(' Lagos to Abuja '), 3);
test('runs of spaces collapse', countWords('Lagos to Abuja'), 3);
test('newlines and indentation do not add words', countWords('\n Lagos\n to\n Abuja\n'), 3);
test('one word', countWords('Lagos'), 1);
test('the empty string has no words', countWords(''), 0);
test('and neither does a string of spaces', countWords(' '), 0);
test('a hyphenated word counts as one', countWords('one-word'), 1);
test('an apostrophe does not split a word', countWords("it's a bus"), 3);
test('the match version agrees on every case', cases.every((t) => countWords(t) === countByMatch(t)), true);
test('the naive split is wrong on runs of spaces', naive('Lagos to Abuja'), 10);
test('because it produces empty strings', 'Lagos to Abuja'.split(' ').filter((w) => w === '').length, 7);
test('and wrong on the empty string', naive(''), 1);
test('which is the whole reason for the guard', ''.split(/\s+/).length, 1);
test('match returns null when nothing matches', ''.match(/\S+/g), null);
test('which is why ?? [] is needed', (''.match(/\S+/g) ?? []).length, 0);
Two separate traps, and the source hints at both. Splitting on a literal ' ' turns 'a b' into a list containing empty strings — the assertion shows a three-word string counted as 11. Splitting on /s+/ treats a whole run as one separator, which also handles tabs and newlines.
Then ''.split(/s+/) returns [''], not [], so its length is 1 and an empty string counts as one word. That is why the guard comes first. The match route has the mirror-image problem: it returns null rather than an empty array when nothing matches, so it needs ?? []. Both assertions are there because both are easy to forget and neither fails loudly.
Worth noting "word" is doing a lot of unexamined work here. This counts whitespace-separated runs, so one-word is one and it's is one, which is probably what you want. For languages that do not put spaces between words, none of this applies, and Intl.Segmenter is the tool.
Common mistakes
- Splitting on
' '. Double spaces make empty pieces and inflate the count. - Forgetting the empty string.
''.split(/\s+/)has length 1, so without a guard empty text counts as one word. - Calling
.lengthon amatchresult directly. When there are no words,matchreturnsnulland.lengththrows aTypeError.
Try it yourself
- Write
readingMinutes(text)that assumes 200 words a minute and rounds up withMath.ceil. - Count only words longer than three letters. (Hint:
filterthe split result.) - Return the longest word instead of the count, using the same
trimandsplit(/\s+/).