Learn JavaScript · lesson 60 of 60 · about 11 minutes
Project: Text Analyser
Count words, find the most common ones and pick out patterns in a piece of text.
What you'll learn
- Split text into words with a regex
- Count words with a Map and find the top ones
- Collect unique matches with a Set
Analysing Sam's post
To finish the page, Sam adds a text analyser under the newest post, postText. It counts the words, 12 words, 10 different, finds the most-used ones, leaving out little words like the and and, Top words: loops (3), make (1), code (1), and lists the post's different hashtags, Hashtags: #coding, #loops. The little words are given as a Set, stopWords; the rest is yours.
The plan
The analyser takes any text and reports on it. It will:
1. Pull out the words with text.toLowerCase().match(/[a-z']+/g), ignoring punctuation
2. Count each word with a Map
3. Sort the counts to find the most common words
4. Collect every different #hashtag with a Set
Steps 1 and 2
const text = "The cat sat. The cat ran! A dog sat.";
const words = text.toLowerCase().match(/[a-z']+/g);
const counts = new Map();
for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);
console.log(words.length, counts.size);
console.log(counts.get("the"), counts.get("sat"));Output
9 6
2 2Top words and hashtags
[...counts] turns the Map into [word, count] pairs, and sort((a, b) => b[1] - a[1]) puts the biggest counts first. For hashtags, /#\w+/g finds them and a Set drops the repeats.
Steps 3 and 4
const counts = new Map([["the", 2], ["cat", 2], ["sat", 2], ["ran", 1], ["a", 1], ["dog", 1]]);
const top = [...counts].sort((a, b) => b[1] - a[1]).slice(0, 2);
console.log(top.map(([w, n]) => `${w}:${n}`).join(" "));
const post = "Fun day #coding #phoebe then more #coding";
const tags = new Set(post.match(/#\w+/g));
console.log([...tags].join(" "));Output
the:2 cat:2
#coding #phoebeWords, counts and tags
The hashtags come out first with replace(/#\w+/g, ""), so they don't count as words, and then toLowerCase().match(/[a-z']+/g) ?? [] gives the words, or an empty array if there are none. A Map counts them, [...wordCounts] turns it into [word, count] pairs, filter leaves out the stop words, and sorting with b[1] - a[1] puts the biggest counts first, with ties staying in the order the words first appeared. For the hashtags, match(/#\w+/g) finds them all, and a Set of their lower-case forms keeps #Coding and #coding as one.
Tip
JavaScript's sort keeps items with equal counts in their original order, so ties stay in the order the words first appeared.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.