How to count words in a string
Short answer
Remove spaces at the edges, split the string by one or more spaces and take the length:
const text = ' JavaScript is a fun language ';
const words = text.trim().split(/\s+/);
console.log(words.length);Output:
5An empty string
Splitting an empty string gives one empty element. Check for this case separately:
const countWords = (text) => (text.trim() === '' ? 0 : text.trim().split(/\s+/).length);
console.log(''.split(/\s+/).length);
console.log(countWords(''));
console.log(countWords('one two'));Output:
1
0
2How many times each word occurs
Count the words in an object where the key is the word:
const words = 'the cat and the dog and the bird'.split(' ');
const counts = {};
for (const word of words) {
counts[word] = (counts[word] ?? 0) + 1;
}
console.log(JSON.stringify(counts));Output:
{"the":3,"cat":1,"and":2,"dog":1,"bird":1}Common mistake
split(' ') with a single space counts every extra space as an empty word:
console.log('one two'.split(' ').length);Output:
3Functions used in this recipe
- String.prototype.split — Splits a string into an array by a separator.
- String.prototype.trim — Removes whitespace from both ends of a string.
- Array.prototype.filter — Creates a new array from the elements that pass a test.