How do I replace all occurrences of a string in JavaScript?
Modern and Classic Approaches to Replacing All Occurrences in JavaScript
Replacing all occurrences of a substring in a JavaScript string can be done in a few ways. The method you choose depends on browser support requirements and your preference for simplicity.
1. Using replaceAll()
(Modern JavaScript, ES2021+)
If you’re working in an environment that supports ES2021 or newer, the simplest solution is the built-in replaceAll()
method. It returns a new string, with all occurrences of the target substring replaced:
const original = "Hello, world! Hello, everyone!"; const result = original.replaceAll("Hello", "Hi"); console.log(result); // "Hi, world! Hi, everyone!"
Key Points:
- No need for regular expressions.
- Clean and easy to read.
- Ensure the runtime (browser, Node.js version, etc.) supports
replaceAll()
.
2. Using String.replace()
with a Global Regular Expression (For Wider Compatibility)
If replaceAll()
is not available, you can use replace()
with a global regular expression. The g
(global) flag ensures that all matches are replaced, not just the first occurrence.
const original = "Hello, world! Hello, everyone!"; const result = original.replace(/Hello/g, "Hi"); console.log(result); // "Hi, world! Hi, everyone!"
Key Points:
- This approach uses a regular expression literal with the
g
flag. - Works in all modern browsers and older environments.
- Be mindful of special characters in the substring that may need escaping if you use it directly in a regex.
3. Creating a Global Regex Dynamically
If the substring to replace is stored in a variable and may contain special regex characters, you can dynamically create a safe regex using RegExp
:
const original = "Hello, world! Hello, everyone!"; const search = "Hello"; const regex = new RegExp(search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), "g"); const result = original.replace(regex, "Hi"); console.log(result); // "Hi, world! Hi, everyone!"
Key Points:
- The
replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
escapes any special regex characters. - Useful when the substring is user-defined or not known in advance.
Strengthening Your JavaScript Knowledge
String manipulation is a fundamental skill in JavaScript. As you tackle tasks like replacing substrings, consider building a strong foundation in the language’s core features:
- Grokking JavaScript Fundamentals: Ideal for beginners and those wanting to solidify their understanding of modern JavaScript. By mastering these essentials, you’ll confidently work with strings, arrays, and objects, and apply best practices in real-world scenarios.
In Summary
To replace all occurrences of a string in JavaScript:
- Use
replaceAll()
if supported:original.replaceAll("old", "new")
. - Use a global regex with
replace()
for broader compatibility:original.replace(/old/g, "new")
.
By selecting the right approach for your environment, you’ll efficiently handle text processing and ensure your code remains clean, maintainable, and compatible.