Skip to curriculum
Jump to the editor

2.1. Reverse a string, its words, and each word

Easy
Topics

This question is in

2. Strings and text
10–15 min

Reversing text comes up in palindrome checks, right-to-left display tricks, and as the warm-up to many string problems. It also shows how JavaScript stores text: reversing "abπŸ˜€" the quick way turns the emoji into two broken halves. This problem has three versions: reverse every character, reverse the order of the words, and reverse each word while it stays in its place.

Write three functions in reverse.js.

Signature

JAVASCRIPT
function reverseString(text)   // the characters in reverse order
function reverseWords(text)    // the words in reverse order
function reverseEachWord(text) // each word reversed, in place

A word is a run of characters that are not whitespace (spaces, tabs, new lines). Punctuation belongs to the word it touches.

Requirements

  1. reverseString reverses every character, spaces and punctuation included. An emoji stays one character: "abπŸ˜€" becomes "πŸ˜€ba".
  2. reverseString returns "" for "" and the same character for a single one.
  3. reverseWords returns the words in reverse order, joined by single spaces. Leading, trailing and repeated whitespace (tabs and new lines too) does not appear in the result.
  4. reverseWords returns "" for an empty or blank string.
  5. reverseEachWord reverses the characters of each word and keeps the words in their order.
  6. reverseEachWord keeps every whitespace character exactly where it was, including repeated spaces, tabs and new lines, and keeps an emoji whole.

Examples

JAVASCRIPT
reverseString("hello");   // "olleh"
reverseString("abπŸ˜€");    // "πŸ˜€ba"
JAVASCRIPT
reverseWords("the sky is blue");     // "blue is sky the"
reverseWords("  hello   world  ");   // "world hello"
reverseWords("Hello, world!");       // "world! Hello,"
JAVASCRIPT
reverseEachWord("hello world");      // "olleh dlrow"
reverseEachWord("  hi   there ");    // "  ih   ereht "

Environment

  • Plain JavaScript in a browser page; the tests call the three globals from reverse.js.
  • Arguments are always strings.
  • Characters made of several code points (a skin-tone emoji, a letter with a combining accent) are not part of the tests.
  • Any built-in may be used.

Hints

  1. What is "πŸ˜€".split("")? What is [..."πŸ˜€"]?
  2. Is there a string method that replaces each match of a pattern with whatever a function returns?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…