Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

5

An 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
2

How 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:

3

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.