.replace() and .replaceAll()
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Swapping Part of a Text
Imagine you have a battle message template like `"NAME uses Thunder!"` and want to replace `"NAME"` with the actual Codémon's name. The `.replace(search, replacement)` method searches a string and swaps a piece of text for another: 1. The first argument is the text you want to find. 2. The second argument is the new text that replaces it.
const template = "NAME uses Thunder!";
const message = template.replace("NAME", "Zap");
console.log(message);Just like `.slice()`, `.replace()` returns a new string without modifying the original. This makes it easy to reuse the same template for different Codémon:
const template = "NAME enters the arena!";
console.log(template.replace("NAME", "Zap"));
console.log(template.replace("NAME", "Pyrochu"));
console.log(template);Exercise 2 — Replacing One vs. Replacing All
Watch out for an important detail: `.replace()` only swaps the first match it finds. If the same word appears again later in the string, those other occurrences remain unchanged:
const chant = "Go Zap! Go Zap! Go Zap!";
console.log(chant.replace("Zap", "Pyrochu"));Only the first `"Zap"` was replaced by `"Pyrochu"`! When you want to replace every single match across the entire string, use `.replaceAll()` instead:
const chant = "Go Zap! Go Zap! Go Zap!";
console.log(chant.replaceAll("Zap", "Pyrochu"));Exercise 3 — Quiz: How Many Changed?
What does this code print?
const s = "a-a-a";
console.log(s.replace("a", "b"));b-a-ab-b-ba-a-abHint : One of the two replacing methods stops early.
Exercise 4 — Fill In the Template
Put `"Aquachu"` in place of `NAME` in the message.
Hint : One method swaps a piece of text, and a name written as text needs its quotes.
Exercise 5 — Cleaning Up Text
`.replaceAll()` is very useful for cleaning up formatted text. For example, if a save file stores titles with underscores (`"_"`) instead of spaces (`" "`), you can make it readable in one step:
const savedTitle = "Aquachu_the_Brave";
const cleanTitle = savedTitle.replaceAll("_", " ");
console.log(cleanTitle);You can also use `.replaceAll()` to delete unwanted characters completely. Simply pass an empty string (`""`) as the second argument so that every match is replaced with nothing:
const messyName = "Z-a-p";
const cleanName = messyName.replaceAll("-", "");
console.log(cleanName);Exercise 6 — Quiz: Removed
What does this code print?
const s = "a b c";
console.log(s.replaceAll(" ", ""));abca b cab c""Hint : Replacing with nothing at all deletes what was found.
Exercise 7 — Chaining Replacements
What if a template has several placeholders to fill in, like `"USER uses MOVE on TARGET!"`? Because `.replace()` always returns a new string, you can chain multiple `.replace()` calls one after another. Each call runs on the string returned by the previous step:
const template = "USER uses MOVE on TARGET!";
const message = template
.replace("USER", "Zap")
.replace("MOVE", "Thunder")
.replace("TARGET", "Florachu");
console.log(message);Use clear placeholders
Always use distinct placeholders in uppercase or brackets (like `"USER"` or `"{USER}"`). If you used a single letter like `"T"`, replacing `"MOVE"` with `"Thunder"` first would add a new `"T"` that the next `.replace("T", ...)` would accidentally overwrite!
Exercise 8 — Clean the Save
Turn every underscore into a space.
Hint : You need the method that doesn't stop at the first match, and a space written as text.
Exercise 9 — replace vs replaceAll
`const s = "a-a";`. Match each expression with its result.
s.replace("a", "b")s.replaceAll("a", "b")s.replaceAll("-", "")"b-a""b-b""aa"Exercise 10 — Battle Message Builder
The game stores one message template and fills it in for every attack of the battle.
Step 1: `buildMessage(attacker, move, target)` takes the template and replaces `{A}` with the attacker, `{M}` with the move and `{T}` with the target, then returns the finished sentence. Step 2: print the message for Zap using Thunder on Florachu, then for Aquachu using Splash on Pyrochu. Step 3: the log line `raw` uses underscores instead of spaces. Print it cleaned up, with every underscore turned into a space.
Expected output:
Zap uses Thunder on Florachu!
Aquachu uses Splash on Pyrochu!
Battle log saved to diskconst template = "{A} uses {M} on {T}!";
const raw = "Battle_log_saved_to_disk";
// Write your function here
// Use it here