The situation
You work on a small writing tool that students use to check their essays against word limits. The page has a text box and a live word count underneath it, written in plain JavaScript (no framework).
Students have noticed that the count jumps when they type two spaces in a row, paste text with line breaks, or indent with tabs, and that an empty box says 1 word. Some have been told their essay is over the limit when it isn't.
"My essay is 498 words in my word processor but your counter says 530. And when the box is empty it says 1."
Your tasks
Task 1: Count words correctly
Fix countWords in counter.js so that:
- A word is any run of characters that are not spaces, tabs or new lines.
- Several spaces, tabs or new lines between words count as one gap.
- Spaces at the start or end of the text don't add words.
- Empty or blank text has 0 words.
Make every test in counter.test.js pass.
Task 2: Try it by hand
Type in the preview: try double spaces, a line break, and clearing the box. The count should match what you'd count yourself.
Project files
index.html
index.js
counter.js
counter.test.js
index.html: the page: a text box (#input) and the count (#count).index.js: connects the two. Every time the text changes it calls countWords and shows the result.counter.js: countWords(text), the logic you are fixing.counter.test.js: the tests for countWords.styles.css, package.json: project setup. You don't need to change these.
How to check your work
- Tests: press ▶ Run tests next to the Tests heading in the bottom panel. They don't re-run on their own, so run them again after each change. PASS means every visible test passed.
- Preview: the bottom-left panel shows the running app and rebuilds as you type. Use Open in new tab above it, or Copy link and paste it into a new tab, to see it full size. That tab follows your edits.
- Your work is saved in this browser. Reset (top right) puts the starting code back.