Sub topic 9
Replacing Text with replace and replaceAll
This chapter assumes you know that string methods return new strings (see "Why Strings Never Change"), that you can search with indexOf and includes, and that you can read basic regular expression syntax such as \d+ and the g flag.
The working model
replace(pattern, replacement) returns a new string with matches swapped out. The original string is never modified. Two choices control what happens:
- The pattern. A plain string matches literally, and only its first occurrence is replaced. A regular expression can match many forms of text, and with the
gflag it replaces every match. - The replacement. A string can contain special
$patterns that insert parts of the match. A function is called once per match, and its return value is inserted.
replaceAll does the same job but always replaces every match.
const text = "cat and cat";
console.log(text.replace("cat", "dog")); // dog and cat
console.log(text.replaceAll("cat", "dog")); // dog and dog
console.log(text.replace(/cat/g, "dog")); // dog and dog
console.log("Cat cat".replace(/cat/gi, "dog")); // dog dog
console.log(text); // cat and cat (unchanged)Special patterns in replacement strings
A replacement string can use these tokens:
| Token | Inserts |
|---|---|
| `$&` | The whole match |
| `$1`, `$2`, ... | Capture group 1, 2, ... |
| `$<name>` | A named capture group |
| `$$` | A literal `$` |
const date = "2026-11-25".replace(/(\d+)-(\d+)-(\d+)/, "$3/$2/$1");
console.log(date); // 25/11/2026
const iso = "2026-11-25".replace(
/(?<y>\d+)-(?<m>\d+)-(?<d>\d+)/,
"$<d>.$<m>.$<y>"
);
console.log(iso); // 25.11.2026
console.log("hello".replace("ell", "[$&]")); // h[ell]oReplacer functions
You can pass a function as the replacement. JavaScript calls it with the match, then each capture group, then the offset of the match, then the whole string. Use a function when the new text depends on the match itself.
const prices = "apple 3, pear 5".replace(/\d+/g, (n) => String(n * 2));
console.log(prices); // apple 6, pear 10
const marked = "a-b-c".replace(/-/g, (match, offset) => `[${offset}]`);
console.log(marked); // a[1]b[3]cCommon errors
- Expecting a string pattern to replace every match.
replace("a", "b")changes only the firsta. UsereplaceAllor a regex withg. $in user-supplied replacement text. If the replacement comes from data,$&or$1inside it gets interpreted. A function's return value is inserted as-is, with no$interpretation:
const userText = "$&";
console.log("total: N".replace("N", userText)); // total: N
console.log("total: N".replace("N", () => userText)); // total: $&- Forgetting to assign the result.
s.replace(...)on its own line does nothing useful, because strings are immutable. Writes = s.replace(...)instead. - Special regex characters in a string pattern. String patterns are always literal, so
"a.b".replaceAll(".", "-")gives"a-b". In a regex,/./gmatches every character.
Exercise
What does "1 + 1 = 2".replace(/\d/g, (d) => d * 10) return, and what does "x.y.z".replace(".", "/") return?
Show answer
The first returns "10 + 10 = 20", because the function runs for each digit and its numeric result is converted to a string. The second returns "x/y.z", because a string pattern is matched literally and only its first occurrence is replaced.
Exercise
Write a call that turns "Smith, John" into "John Smith" using capture groups.
Show answer
"Smith, John".replace(/(\w+), (\w+)/, "$2 $1") returns "John Smith".