How do I replace all occurrences of a string?
Categories:
Mastering String Replacement: How to Replace All Occurrences in JavaScript

Learn various JavaScript methods to efficiently replace all instances of a substring within a string, from basic replace()
with regex to modern replaceAll()
.
Replacing specific parts of a string is a common task in programming. In JavaScript, you often need to replace all occurrences of a particular substring, not just the first one. This article will guide you through different techniques to achieve this, explaining the nuances and best practices for each method.
The String.prototype.replace()
Method with Regular Expressions
The replace()
method is a fundamental string method in JavaScript. By default, when used with a string as its first argument, it only replaces the first occurrence of that string. To replace all occurrences, you must use a regular expression with the global (g
) flag.
const originalString = "Hello world, hello JavaScript!";
// Replacing only the first occurrence (default behavior)
const firstReplace = originalString.replace("hello", "hi");
console.log(firstReplace); // Output: "Hello world, hi JavaScript!"
// Replacing all occurrences using a regular expression with the 'g' flag
const allReplace = originalString.replace(/hello/g, "hi");
console.log(allReplace); // Output: "hi world, hi JavaScript!"
// Case-insensitive replacement using 'gi' flags
const caseInsensitiveReplace = originalString.replace(/hello/gi, "greetings");
console.log(caseInsensitiveReplace); // Output: "greetings world, greetings JavaScript!"
Using replace()
with and without the global flag for string replacement.
.
, *
, +
, ?
, (
, )
, [
, ]
, \
, {
, }
, |
, ^
, $
), you'll need to escape them in your regex pattern. For example, to replace .
you'd use \.
.Introducing String.prototype.replaceAll()
(ES2021)
For a more straightforward approach, JavaScript introduced String.prototype.replaceAll()
in ES2021. This method directly replaces all occurrences of a specified substring without needing a regular expression, making the code cleaner and often more readable for simple string replacements.
const originalString = "The quick brown fox jumps over the lazy dog. The fox is quick.";
// Using replaceAll() to replace all occurrences of a string
const newString = originalString.replaceAll("fox", "cat");
console.log(newString); // Output: "The quick brown cat jumps over the lazy dog. The cat is quick."
// replaceAll() also works with regular expressions, but the 'g' flag is mandatory
try {
originalString.replaceAll(/fox/, "cat"); // Throws TypeError: replaceAll must be called with a global RegExp
} catch (e) {
console.error(e.message);
}
const regexReplaceAll = originalString.replaceAll(/fox/g, "cat");
console.log(regexReplaceAll); // Output: "The quick brown cat jumps over the lazy dog. The cat is quick."
Demonstrating replaceAll()
for simple string and regex replacements.
replaceAll()
simplifies string replacement, it's important to note its browser compatibility. It's widely supported in modern browsers, but if you need to support older environments (like Internet Explorer), you'll need to stick with the replace()
method with a global regex or transpile your code.Choosing the Right Method: A Decision Flow
Deciding between replace()
with a global regex and replaceAll()
depends on your specific needs and target environment. Consider the following flow to make an informed choice.
flowchart TD A[Start] --> B{Need to replace all occurrences?} B -->|No| C[Use `string.replace("search", "replace")`] B -->|Yes| D{Target environment supports ES2021 `replaceAll()`?} D -->|Yes| E{Search string is a literal string (no special regex chars)?} E -->|Yes| F[Use `string.replaceAll("search", "replace")`] E -->|No| G[Use `string.replaceAll(/search/g, "replace")`] D -->|No| H[Use `string.replace(/search/g, "replace")`] F --> I[End] G --> I[End] C --> I[End] H --> I[End]
Decision flow for choosing the appropriate string replacement method.
Performance Considerations
For most common use cases, the performance difference between replace(/string/g, ...)
and replaceAll('string', ...)
is negligible. However, if you're dealing with extremely large strings or performing replacements in a tight loop, replaceAll()
might offer a slight performance edge due to its optimized native implementation for literal string replacements. When using regular expressions, the performance will largely depend on the complexity of your regex pattern.