Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT
2.5. Replace every space with an underscore, three ways
Easy
Topics
This question is in
2. Strings and textFile 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
function withReplaceAll(text) // a string
function withSplitJoin(text) // a string
function withLoop(text) // a stringRequirements
Each of the three functions:
- Replaces every space character (
" ", U+0020) with"_", not only the first one. - Replaces spaces next to each other one for one: two spaces become two underscores.
- Replaces spaces at the start and the end too.
- Leaves every other character alone, including tabs, new lines and the no-break space (U+00A0).
- Returns text with no spaces unchanged, and
""for"".
And each one uses its own way:
withReplaceAlluses a replace method of strings, withoutsplitorjoin.withSplitJoinusessplitandjoin, withoutreplaceorreplaceAll.withLoopbuilds the result with a loop, withoutreplace,replaceAll,splitorjoin.
Examples
withReplaceAll("hello world"); // "hello_world"
withSplitJoin("a b c d"); // "a_b_c_d"
withLoop(" two "); // "__two__"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
- What does
"a b c".replace(" ", "_")return? - 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β¦