Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Collapse Whitespace

Beyond the Coursemedium

Implement `collapseSpaces(s)` that replaces any run of whitespace with a single space and trims the ends.

Sample tests

Input: collapseSpaces("a b c")
Output: "a b c"
Input: collapseSpaces(" hi ")
Output: "hi"

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Forgetting the global flag only collapses the first run.

Learning resources

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

Replacing /\s+/g with a single space and trimming normalizes irregular whitespace.

Loading...
⌘/Ctrl + Enter

Run your code to see results.