Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Count Words with Regex

Beyond the Coursemedium

Implement `countWords(s)` returning the number of word tokens in `s`, matching runs of word characters.

Sample tests

Input: countWords("hello world")
Output: 2
Input: countWords("")
Output: 0

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Splitting on spaces miscounts punctuation-separated words.

Learning resources

  • MDN: Regular expressions
Approach & explanation (try first)

Matching /\b\w+\b/g counts word tokens regardless of punctuation.

Loading...
⌘/Ctrl + Enter

Run your code to see results.