Sub topic 9
Replacing Text with replace and replaceAll
This chapter assumes you know how string immutability works, how indexOf and includes search text, and the basics of regular expression syntax such as character classes, quantifiers, and capture groups. Both methods covered here return a new string. The original string never changes, so you have to keep the result:
let title = "draft: report";
title.replace("draft: ", ""); // result discarded, title unchanged
title = title.replace("draft: ", ""); // reassign to keep the change
console.log(title); // reportThe Two Methods at a Glance
replace(pattern, replacement) and replaceAll(pattern, replacement) take the same two arguments. The pattern can be a string or a regular expression. The replacement can be a string or a function. How many matches get replaced depends on which method you call and what kind of pattern you pass.
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
const date = "2026-11-25".replace(/(\d+)-(\d+)-(\d+)/, "$3/$2/$1");
console.log(date); // 25/11/2026
const prices = "apple 3, pear 5".replace(/\d+/g, (n) => String(n * 2));
console.log(prices); // apple 6, pear 10| Call | Pattern type | Matches replaced |
|---|---|---|
| `replace("cat", ...)` | string | first only |
| `replace(/cat/, ...)` | regex without `g` | first only |
| `replace(/cat/g, ...)` | regex with `g` | all |
| `replaceAll("cat", ...)` | string | all |
| `replaceAll(/cat/g, ...)` | regex with `g` | all |
| `replaceAll(/cat/, ...)` | regex without `g` | throws `TypeError` |
The First-Match-Only Trap
The most common bug with replace is expecting a string pattern to replace every occurrence. It doesn't. Before replaceAll was added in ES2021, developers worked around this with split(x).join(y) or with a global regex. Both still work, but replaceAll with a string states what you mean and needs no escaping.
const slug = "my blog post title";
console.log(slug.replace(" ", "-")); // my-blog post title (bug)
console.log(slug.replaceAll(" ", "-")); // my-blog-post-title
console.log(slug.split(" ").join("-")); // my-blog-post-title (older idiom)replaceAll requires a global regex on purpose. A call like replaceAll(/x/, ...) contradicts itself, because the method name says "all" and the regex says "first only". The language throws instead of guessing which one you meant:
try {
"aXbX".replaceAll(/x/i, "-");
} catch (e) {
console.log(e instanceof TypeError); // true
}
console.log("aXbX".replaceAll(/x/gi, "-")); // a-b-Special Patterns in the Replacement String
A replacement string is not always taken literally. A $ followed by certain characters is treated as a substitution. This applies even when the pattern is a plain string.
| Pattern | Inserts |
|---|---|
| `$$` | a literal `$` |
| `$&` | the whole matched text |
| `` $` `` | the text before the match |
| `$'` | the text after the match |
| `$1`, `$2`, ... | the numbered capture group |
| `$<name>` | the named capture group |
const name = "Lovelace, Ada";
console.log(name.replace(/(\w+), (\w+)/, "$2 $1")); // Ada Lovelace
console.log(name.replace(/(?<last>\w+), (?<first>\w+)/, "$<first> $<last>")); // Ada Lovelace
console.log("abc".replace("b", "[$&]")); // a[b]c
console.log("abc".replace("b", "[$`|$']")); // a[a|c]c
console.log("cost: 5".replace("5", "$$5")); // cost: $5const userText = "Pay $& now";
console.log("Hello NAME".replace("NAME", userText)); // Hello Pay NAME now
console.log("Hello NAME".replace("NAME", () => userText)); // Hello Pay $& nowReplacer Functions
When the replacement depends on what matched, pass a function. JavaScript calls it once per match and inserts its return value, converted to a string. Dollar patterns in the return value are never expanded.
The function receives these arguments in order:
- The full match.
- One argument per capture group (
undefinedfor a group that didn't take part in the match). - The offset where the match starts.
- The whole original string.
- An object of named groups, passed only when the regex has named groups.
const s = "x=1, y=22";
const out = s.replace(/(\w)=(\d+)/g, (match, key, value, offset) => {
console.log(match, key, value, offset);
return `${key.toUpperCase()}:${value}`;
});
// x=1 x 1 0
// y=22 y 22 5
console.log(out); // X:1, Y:22The number of capture groups changes where offset falls in the argument list. When you use named groups, a rest parameter avoids counting positions, because the groups object is always last:
const iso = "2026-11-25";
const eu = iso.replace(/(?<y>\d+)-(?<m>\d+)-(?<d>\d+)/, (...args) => {
const { y, m, d } = args.at(-1);
return `${d}.${m}.${y}`;
});
console.log(eu); // 25.11.2026Replacer functions are useful for lookups, such as filling a template from an object:
const data = { user: "Ada", count: 3 };
const tpl = "Hi {user}, you have {count} messages. {missing}";
const filled = tpl.replace(/\{(\w+)\}/g, (whole, key) =>
key in data ? String(data[key]) : whole
);
console.log(filled); // Hi Ada, you have 3 messages. {missing}Returning whole for unknown keys leaves those placeholders untouched.
Building a Regex from User Input
Sometimes you need regex features, such as the i flag, around text you don't control. Passing that text straight to new RegExp is a bug, because characters like ., +, and ( are regex syntax:
const needle = "1.5";
const text = "105 and 1.5";
console.log(text.replace(new RegExp(needle, "g"), "N")); // N and N (wrong: . matched "0")
console.log(text.replaceAll(needle, "N")); // 105 and NIf you only need exact matching, use replaceAll with a string. If you need flags as well, escape the input first:
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
const re = new RegExp(escapeRegExp("1.5"), "gi");
console.log("105 and 1.5".replace(re, "N")); // 105 and NEdge Cases
An empty string pattern matches at position 0. With replaceAll, it matches between every UTF-16 code unit:
console.log("abc".replace("", "-")); // -abc
console.log("abc".replaceAll("", "-")); // -a-b-c-Because empty matches fall between code units, this can split an emoji's surrogate pair in half. The chapter on Unicode explains why.
Matching is case-sensitive unless the regex has the i flag. replaceAll with a string pattern has no case-insensitive option, so use /pattern/gi for that.
Non-string arguments are converted. "a1b1".replaceAll(1, "-") gives "a-b-" because the number 1 becomes the string "1". A replacement of undefined inserts the text "undefined", which usually means you forgot a return in a replacer function:
console.log("a-b".replace("-", (m) => { m.toUpperCase(); })); // aundefinedbGlobal regexes are safe to reuse. replace resets the lastIndex of a g regex before it starts. Calling it twice with the same regex object gives the same result each time, unlike test and exec.
Replacements are not rescanned. Inserted text is never matched again, so "aa".replaceAll("a", "aa") returns "aaaa" and does not loop forever.
Exercise
What does "a.b.c".replace(".", "-") return, and what does "a.b.c".replace(/./g, "-") return? Explain the difference.
Show answer
The first returns "a-b.c": a string pattern is matched literally, and replace changes only the first match. The second returns "-----": in a regex, . matches any character, and the g flag replaces every match, so all five characters become dashes. To replace every literal dot, use "a.b.c".replaceAll(".", "-") or /\./g, which both give "a-b-c".
Exercise
Write a function maskEmail(email) that keeps the first character of the local part and replaces the rest of the local part with asterisks of the same length. For example, maskEmail("[email protected]") should return "a**@example.com".
Show answer
Capture the first character and the rest of the local part, then build the mask with a replacer function: const maskEmail = (email) => email.replace(/^(.)([^@]*)@/, (m, first, rest) => first + "*".repeat(rest.length) + "@");. A replacer function is needed because the number of asterisks depends on the length of the match, and a fixed replacement string can't express that.
Exercise
A greeting template uses tpl.replace("{name}", name). A user enters the name $'. For the template "Hi {name}!", what is the output, and how do you fix it?
Show answer
$' expands to the text after the match, which is "!", so the output is "Hi !!". Fix it by passing a function so the value is inserted literally: tpl.replace("{name}", () => name), which gives "Hi $'!". If the placeholder can appear more than once, use replaceAll with the same function.