Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Word Count

Data Structures, Operators & Stringsmedium

Course · Section 9: Data Structures, Modern Operators and Strings · Lecture 128: Working With Strings - Part 1

Implement `wordCount(s)` returning the number of words in `s`, where words are separated by any whitespace and surrounding whitespace is ignored.

Sample tests

Input: wordCount("the quick brown fox")
Output: 4
Input: wordCount(" hello world ")
Output: 2

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • An empty or all-space string splits to [''], which would count as 1 without a filter.

Learning resources

  • MDN: String
Approach & explanation (try first)

Trimming and splitting on \s+ with a filter handles extra and leading/trailing whitespace correctly.

Loading...
⌘/Ctrl + Enter

Run your code to see results.