Strings · intermediate
JavaScript Program to Count Word Frequency in a String
Count how often each word appears in a text in JavaScript with a Map, ignore case and punctuation with a regex, and sort the words by frequency.
- Map
- match() with a regex
- sort() with a compare function
- padEnd()
Counting words is the first step of many text tasks, from keyword analysis to word clouds. A Map is the natural counter in JavaScript: it keeps insertion order and accepts any string as a key, even ones like "constructor" that clash with plain object properties.
The program
const text = `The cat sat on the mat.
The dog sat on the log.`;
const counts = new Map();
for (const word of text.toLowerCase().match(/[a-z']+/g)) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
const sorted = [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
for (const [word, n] of sorted) {
console.log(word.padEnd(4), n);
}the 4
on 2
sat 2
cat 1
dog 1
log 1
mat 1How it works
- match(/[a-z']+/g) returns every run of letters (and apostrophes), which drops punctuation such as the full stops.
- counts.get(word) ?? 0 is the current count, or 0 for a new word, and set() stores the count plus one.
- [...counts] turns the Map into an array of [word, count] pairs.
- The compare function sorts by count, highest first; for equal counts, localeCompare sorts alphabetically. padEnd(4) lines up the numbers.
Watch it run line by line
Watch the counts Map in the global frame: it gains an entry for each new word, and the highlighted value shows the count that just changed.
“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: With reduce() and an object
reduce() can build the counts in one expression. A plain object works here, but a word like "constructor" or "__proto__" would collide with built-in properties; Object.create(null) avoids that.
const words = "the cat sat on the mat the end".split(" ");
const counts = words.reduce((acc, w) => {
acc[w] = (acc[w] ?? 0) + 1;
return acc;
}, Object.create(null));
console.log(counts.the, counts.cat, counts.dog ?? 0);3 1 0Common mistakes
- Splitting with split(" "), which keeps punctuation ("mat.") and creates empty strings when there are two spaces.
- Calling match() on text with no letters: it returns null, so for...of throws. Use ?? [].
- Sorting with a compare function that returns a boolean (b[1] > a[1]): sort expects a negative, zero or positive number.
Try it yourself
- Ignore common words such as "the" and "on" with a Set of stop words.
- Print the three most frequent words only.
Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.