Replace all occurrences of a string in JavaScript
Intermediate · 3 min read
Swapping one word for another across a whole piece of text is a daily task: fixing a typo in every product description, filling in a template, cleaning up data before saving it. JavaScript's replace looks like the obvious tool, but with a plain string it only changes the first match. That's one of the most common "it worked on my test data" bugs.
In this tutorial you will swap every danfo in a sentence for keke three ways, see why one of them is refused with an error, and learn what the $ sign does inside a replacement. You need to know what a string is and how to call a method on it.
replace and replaceAll
Both methods take two arguments: what to look for, and what to put in its place. Both return a new string. Strings in JavaScript can't be changed in place, so the original text stays exactly as it was.
replace(find, replacement)changes the first match.replaceAll(find, replacement)changes every match.
A quick look at regular expressions
A regular expression is a search pattern written between slashes, like /danfo/. A letter after the closing slash is a flag that changes how it searches. The g flag means "global": find every match, not just the first. So /danfo/g means "every danfo".
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
109 Replace every occurrence, not just the first
fairSwap every danfo in a sentence for keke. Try replace with a string, replaceAll, and a global regex — then find out what $ does inside a replacement.
Stuck? Three hints, smallest first
- 1.
replacewith a string replaces the first match only. - 2.
replaceAllwith a regex insists that regex be global. - 3. In a replacement string
$&is the match and$$is a literal dollar sign.
Step 1: replace stops after one
const line = 'danfo, danfo and one more danfo';
console.log(line.replace('danfo', 'keke')); // keke, danfo and one more danfo
Only the first danfo changed. If your test sentence had only one, you'd never notice.
Step 2: replaceAll changes every one
const line = 'danfo, danfo and one more danfo';
console.log(line.replaceAll('danfo', 'keke')); // keke, keke and one more keke
console.log(line); // danfo, danfo and one more danfo
replaceAll says exactly what you mean. The second line proves the original is untouched: the changed text only exists in the value replaceAll returned.
Step 3: the older way, a global regex
Before replaceAll was added, you used replace with a global regular expression:
const line = 'danfo, danfo and one more danfo';
console.log(line.replace(/danfo/g, 'keke')); // keke, keke and one more keke
Same result. You'll see this a lot in older code. The danger is forgetting the g: line.replace(/danfo/, 'keke') quietly changes only the first match again.
Step 4: replaceAll refuses a regex without g
replaceAll protects you from that mistake:
const line = 'danfo, danfo and one more danfo';
try {
line.replaceAll(/danfo/, 'keke');
} catch (err) {
console.log(err.name); // TypeError
}
A regex without g would mean "replace one", which contradicts the name replaceAll. Instead of guessing what you meant, JavaScript throws a TypeError. A loud error like this is easier to fix than a quiet wrong answer.
Step 5: the dollar sign is special
Inside a replacement string, $ starts a special code. $& means "the text that was matched":
console.log('fare'.replace('fare', '$& and $&')); // fare and fare
That is handy on purpose, but surprising when the replacement is a price. A lone $ has to be written $$ to come out as one dollar sign:
console.log('price'.replace('price', 'US$$5')); // US$5
This bites when the replacement comes from data, like text a user typed. If it happens to contain $&, it gets interpreted instead of copied.
Step 6: pass a function instead
If the second argument is a function, whatever it returns is inserted exactly as it is, with no special codes:
console.log('price'.replace('price', () => 'US$5')); // US$5
No doubling needed. When the replacement is data rather than something you typed into the code yourself, a function is the safe choice.
The full solution
The answer panel runs all three replacements, catches the TypeError, and checks the $&, $$ and function cases. It also confirms that the original line still has three danfos and that replacing a word that isn't there changes nothing. Press Run to see the output.
const line = 'danfo, danfo and one more danfo';
const first = line.replace('danfo', 'keke');
const all = line.replaceAll('danfo', 'keke');
const viaRegex = line.replace(/danfo/g, 'keke');
let nonGlobalThrew = '';
try {
line.replaceAll(/danfo/, 'keke');
} catch (err) {
nonGlobalThrew = err.name;
}
// $ is special inside a replacement string, whichever method you used.
const doubled = 'fare'.replace('fare', '$& and $&');
const literalDollar = 'price'.replace('price', 'US$$5');
const viaCallback = 'price'.replace('price', () => 'US$5');
console.log(first);
console.log(all);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('replace with a string changes the first only', first, 'keke, danfo and one more danfo');
test('replaceAll changes every one', all, 'keke, keke and one more keke');
test('a global regex does the same', viaRegex, all);
test('replaceAll with a non-global regex is refused', nonGlobalThrew, 'TypeError');
test('$& in a replacement means the whole match', doubled, 'fare and fare');
test('so a lone $ needs doubling to survive', literalDollar, 'US$5');
test('a function replacement is taken literally, no escaping needed', viaCallback, 'US$5');
test('strings are immutable, so the original is untouched', line.split('danfo').length - 1, 3);
test('and a needle that is absent changes nothing', line.replaceAll('okada', 'keke'), line);
replace with a string argument replaces one occurrence, which is the single most common cause of "it worked on my test data". replaceAll exists to say what you meant; before it, the only way was a global regex, and forgetting the g gave the same one-match behaviour silently. replaceAll refuses a non-global regex outright rather than repeating that mistake — a rare case of the language choosing a loud error over a plausible guess.
The $ rules bite when the replacement is data rather than a literal. Any user-supplied text containing $&, $1 or $' will be interpreted, so pasting a price of $5 into a replacement string is a real bug. Pass a function instead: its return value is inserted verbatim, no escaping and no surprises. And note none of this mutates — replace returns new text, so ignoring the return value is a no-op.
Common mistakes
- Using
replacewith a string and expecting every match to change. Only the first one does. UsereplaceAll. - Forgetting the
gon a regex.replace(/x/, ...)changes one match.replaceAll(/x/, ...)throws. - Ignoring the return value.
line.replaceAll('danfo', 'keke');alone changes nothing. Store the result:const fixed = line.replaceAll(...).
Try it yourself
- Replace every comma in
'Ikeja,Yaba,Lekki'with', 'to get'Ikeja, Yaba, Lekki'. - Fill a template: turn
'Hello {name}, your bus leaves at {time}'into a real sentence with tworeplaceAllcalls. - Use a regex with the
iflag as well asg(/danfo/gi) to replaceDanfoandDANFOtoo.