JavaScript replace vs replaceAll Explained
In JavaScript, manipulating strings often requires substituting parts
of text with new values. While both
String.prototype.replace and
String.prototype.replaceAll achieve this, their primary
difference lies in how they handle multiple occurrences of a target
substring: replace() changes only the first match by
default, whereas replaceAll() updates every occurrence
throughout the entire string without requiring a global regular
expression.
String Pattern Differences
When passing a string as the search pattern, the difference in behavior between the two methods is immediately apparent:
const text = "The red fox jumped over the red fence.";
// replace() only affects the first instance
const replaced = text.replace("red", "blue");
console.log(replaced);
// Output: "The blue fox jumped over the red fence."
// replaceAll() affects every instance
const replacedAll = text.replaceAll("red", "blue");
console.log(replacedAll);
// Output: "The blue fox jumped over the blue fence."Before replaceAll() was introduced in ECMAScript 2021
(ES12), developers had to use regular expressions with the global flag
(/g) to achieve a full replacement of a string literal.
Regular Expression Handling
Both methods support regular expressions as search patterns, but they enforce different rules regarding regex flags:
1.
String.prototype.replace
Accepts regular expressions with or without the global
(g) flag:
const text = "apple orange apple";
// Replaces only the first match
console.log(text.replace(/apple/, "banana"));
// Output: "banana orange apple"
// Replaces all matches using the /g flag
console.log(text.replace(/apple/g, "banana"));
// Output: "banana orange banana"2.
String.prototype.replaceAll
Requires the global (g) flag if a regular expression is
passed. If you provide a non-global regular expression, JavaScript
throws a TypeError.
const text = "apple orange apple";
// Valid: Uses the /g flag
console.log(text.replaceAll(/apple/g, "banana"));
// Output: "banana orange banana"
// Invalid: Throws TypeError: String.prototype.replaceAll called with a non-global RegExp argument
console.log(text.replaceAll(/apple/, "banana"));Summary of Key Differences
| Feature | replace() |
replaceAll() |
|---|---|---|
| String parameter | Replaces the first match | Replaces all matches |
Non-global RegExp
(/pattern/) |
Replaces the first match | Throws a TypeError |
Global RegExp
(/pattern/g) |
Replaces all matches | Replaces all matches |
| ECMAScript Standard | ES3 (Standard since early JS) | ES2021 (Modern environments) |
When to Use Each
- Use
replace()when you explicitly need to substitute only the first instance of a substring or when working with non-global regular expressions. - Use
replaceAll()when you need to replace all occurrences of a string literal, as it improves code readability by removing the need for regular expressions and escaping special characters.