What is the difference between replace and replaceAll on strings?
replace with a string pattern changes only the first match. replaceAll changes every match. With a regular expression, replace needs the g flag to change all matches, and replaceAll throws if the regex lacks it.
Explain it simply
replace is like hitting "Replace" once in a text editor: it fixes the first match and stops. replaceAll is "Replace All".
When the first argument is a string, replace touches only the first occurrence. You can get "all" by using a regex with the g (global) flag: /-/g. replaceAll was added so that you do not need a regex for the simple case.
Both return a new string; the original is unchanged. The replacement can also be a function, called for each match, which is handy for computed replacements.
Example
console.log("a-b-c".replace("-", "+")); // Output: a+b-c
console.log("a-b-c".replaceAll("-", "+")); // Output: a+b+c
console.log("a-b-c".replace(/-/g, "+")); // Output: a+b+c
try {
"a-b".replaceAll(/-/, "+");
} catch (e) {
console.log(e.name); // Output: TypeError
}
console.log("3 4".replace(/\d/g, (d) => d * 2)); // Output: 6 8What to say in the interview
"With a string pattern, replace changes the first occurrence only and replaceAll changes all of them. With a regex, I need the g flag for replace, and replaceAll requires it. Both return a new string."
Common mistakes
- Using replace("-", "+") on a string and expecting every hyphen to change.