Scriptdrill

Level 1: Basics Exercise 5 of 45 Free

Reverse the words

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Return the words of `s` in reverse order, separated by single spaces. Words are separated by any whitespace (spaces, tabs or newlines), and there is no whitespace at the start or end of the result.

What this exercise teaches

Trimming first avoids empty words at either end, and splitting on /\s+/ treats any run of spaces, tabs or newlines as one separator. An all-whitespace string trims to "", which splits into [""] and joins back to "".

A hint if you get stuck

Trim, split on runs of whitespace with `/\s+/`, reverse, then join with `" "`. Watch the empty string.

Try it now, no account needed

This exercise is free. Open it on the practice page, solve it, and get instant feedback with a hint and a worked solution after two tries.

Open this exercise

More exercises in Basics