JavaScript bootcamp · Lab 12

Count the words

easyStrings8 minLesson: String Methods

Read the question, write JavaScript on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read one line of text and log how many words it contains.

Splitting on a run of whitespace (not a single space) means double spaces do not create empty "words".

Input. One line of text.

Output. One integer: the word count.

Examples

Example 1
Input
the quick brown fox
Output
4
Example 2 — Extra spaces do not add phantom words.
Input
hello   world
Output
2
Hint
  1. split(/\s+/) splits on any run of whitespace.
  2. Trim first and filter out empties: line.trim().split(/\s+/).filter(Boolean).
Show correct code

Peek only after you have tried. You can still Check your own version.

const line = readLine();
const words = line.trim().split(/\s+/).filter(Boolean);
console.log(words.length);
main.jsconsole.log · readLine() · Ctrl + Enter
ResultIdle
Run to see output. Check grades the tests.