Count words split by any whitespace in JavaScript
Intermediate · 3 min read
Word counts appear everywhere: an essay box that says "250 words", a tweet-length check, a reading-time estimate on a blog. Counting words sounds trivial, and the obvious one-liner gets most sentences right. It also says that an empty box contains one word.
In this tutorial you will write countWords so that it handles extra spaces, tabs and new lines, and gives 0 for an empty or blank string. You should know how split works. The short regular expression we need is explained below.
Whitespace
Whitespace is any character you can't see but that makes space: an ordinary space, a tab (\t) and a new line (\n). People don't type neat single spaces. They hit space twice, paste text with tabs, or press Enter between words. A good word count treats any run of whitespace as one gap.
The pattern \s+
In a regular expression, \s matches one whitespace character of any kind, and + means "one or more". So /\s+/ matches a run of whitespace, however long. Passed to split, it cuts at every gap between words.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
35 Count the words in a sentence
fairCount the words in a sentence, treating any run of whitespace as one separator. Get it right for an empty string and for a string of only spaces.
Stuck? Three hints, smallest first
- 1. Trim first, then split on
/\s+/. - 2. Splitting an empty or blank string still produces an array with something in it, so guard.
- 3. Decide deliberately whether a hyphenated word is one word or two.
Step 1: the naive version
The first idea is to split on a single space:
console.log('the quick fox'.split(' ').length); // 3
console.log('the quick fox'.split(' ').length); // 7
The first is right. The second is wrong: between two spaces in a row, split(' ') finds an empty word, and those empty strings are counted too.
Step 2: split on runs of whitespace
console.log('the quick fox'.split(/\s+/).length); // 3
console.log('a\nb\tc'.split(/\s+/).length); // 3
Each run of spaces is one gap now, and new lines and tabs count as gaps too.
Step 3: spaces at the ends
console.log(' hi '.split(/\s+/)); // [ '', 'hi', '' ]
console.log(' hi '.trim().split(/\s+/)); // [ 'hi' ]
Whitespace at the start or end leaves empty pieces before or after the words. trim() removes whitespace from both ends first, so only real words are left.
Step 4: empty and blank strings
Now try text with no words at all:
console.log(''.split(/\s+/)); // [ '' ]
console.log(' '.split(/\s+/)); // [ '', '' ]
console.log(' '.trim().split(/\s+/)); // [ '' ]
All three arrays have something in them, so .length would report 1, 2 and 1 words for text that has none. Trimming turns the blank string into an empty one, but splitting an empty string still gives one empty piece. That is just how split works: with nothing to cut, you get the whole (empty) string back.
Step 5: guard the empty case
So after trimming, check for an empty string and return 0 before splitting:
const countWords = (text) => {
const trimmed = text.trim();
return trimmed === '' ? 0 : trimmed.split(/\s+/).length;
};
console.log(countWords('the quick fox')); // 3
console.log(countWords('the quick fox')); // 3
console.log(countWords(' hi ')); // 1
console.log(countWords('')); // 0
console.log(countWords(' ')); // 0
That guard is the heart of this exercise. Everything else is one line.
Step 6: decide what a word is
const countWords = (text) => {
const trimmed = text.trim();
return trimmed === '' ? 0 : trimmed.split(/\s+/).length;
};
console.log(countWords('well-known fact')); // 2
console.log(countWords('hi, there!')); // 2
console.log(countWords("it's fine")); // 2
This version counts runs of characters that aren't whitespace. So well-known is one word, punctuation stays attached to its word, and it's is one word. That is what most word counters do, but it is a choice. If you want hyphenated words to count as two, you would split on hyphens too.
The full solution
Here is the complete answer: countWords with the trim and the guard, and checks for extra spaces, tabs, empty input and punctuation. Press Run and look at the line that shows why the guard is needed.
const countWords = (text) => {
const trimmed = text.trim();
return trimmed === '' ? 0 : trimmed.split(/\s+/).length;
};
console.log("countWords('the quick fox') :", countWords('the quick fox'));
console.log("countWords(' ') :", countWords(' '));
console.log("' '.split(/\\s+/) :", ' '.split(/\s+/), '<- length 2, hence the guard');
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('the quick fox'), 3);
test('extra spaces between words add nothing', countWords('the quick fox'), 3);
test('leading and trailing spaces are trimmed first', countWords(' hi '), 1);
test('an empty string has no words', countWords(''), 0);
test('and neither does a string of only spaces', countWords(' '), 0);
test('without the guard the split would have reported two', ' '.split(/\s+/).length, 2);
test('newlines and tabs separate words too', countWords('a\nb\tc'), 3);
test('a hyphenated word counts as one', countWords('well-known fact'), 2);
test('punctuation does not split a word either', countWords('hi, there!'), 2);
test('so "word" here means a run of non-whitespace', countWords("it's fine"), 2);
The guard is the exercise. ''.split(/\s+/) is [''] and ' '.split(/\s+/) is ['', ''], so the obvious one-liner reports 1 and 2 words for input that has none. Trimming fixes the second case and not the first, which is why the explicit empty check is there.
"Word" is a definition, not a fact. This version counts runs of non-whitespace, so 'well-known' is one word and 'hi,' includes its comma. If you need linguistic words, match /[\p{L}\p{N}']+/gu instead and decide about the apostrophe on purpose.
Common mistakes
- Splitting on
' '. Double spaces create empty words. Split on/\s+/. - Skipping
trim(). Leading or trailing whitespace adds an empty word. - No empty check.
''.split(/\s+/).lengthis 1. Return 0 when the trimmed text is empty.
Try it yourself
- Write
readingTime(text)that returns the minutes needed at 200 words per minute, rounded up. - Change
countWordsso'well-known'counts as two words. - Write
longestWord(text)using the same split.