Skip to curriculum
Jump to the editor

2.5. Replace every space with an underscore, three ways

Easy
Topics

This question is in

2. Strings and text
5–15 min

File names, ids, analytics event names and database keys often cannot contain spaces, so "monthly report" becomes "monthly_report". It is a one-line job, and a classic first try changes only the first space. Writing it three different ways shows what each tool in JavaScript's string kit does: a replace method, splitting and joining, and a plain loop.

Write three functions in underscores.js. Each replaces every space with an underscore.

Signature

JAVASCRIPT
function withReplaceAll(text) // a string
function withSplitJoin(text)  // a string
function withLoop(text)       // a string

Requirements

Each of the three functions:

  1. Replaces every space character (" ", U+0020) with "_", not only the first one.
  2. Replaces spaces next to each other one for one: two spaces become two underscores.
  3. Replaces spaces at the start and the end too.
  4. Leaves every other character alone, including tabs, new lines and the no-break space (U+00A0).
  5. Returns text with no spaces unchanged, and "" for "".

And each one uses its own way:

  1. withReplaceAll uses a replace method of strings, without split or join.
  2. withSplitJoin uses split and join, without replace or replaceAll.
  3. withLoop builds the result with a loop, without replace, replaceAll, split or join.

Examples

JAVASCRIPT
withReplaceAll("hello world");   // "hello_world"
withSplitJoin("a b c d");        // "a_b_c_d"
withLoop("  two  ");             // "__two__"
JAVASCRIPT
withReplaceAll("a\tb c");        // "a\tb_c": the tab stays
withSplitJoin("");               // ""
withLoop("nospace");             // "nospace"

Environment

  • Plain JavaScript in a browser page; the tests call the three globals from underscores.js.
  • The argument is always a string.
  • While a function is tested, the built-ins it must not use are replaced with functions that throw.

Hints

  1. What does "a b c".replace(" ", "_") return?
  2. What does "a b".split(" ") return? Count the items.

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…