How to Replace All Occurrences of a String in JavaScript
When working with strings in JavaScript, you might want to replace all occurrences of a specific word or substring — not just the first one.
For example, using string.replace('abc', '') will only remove the first instance of 'abc'. Developers often wonder how to modify this behavior to remove or replace every occurrence of a substring efficiently and safely.
Let’s explore the correct ways to do this in both modern JavaScript (ES2021 and later) and older browsers.
How to Replace All Occurrences of a String in JavaScript
coldshadow44 on 2025-10-15
Make a comment
_
2025-10-15
In older versions of JavaScript, the String.replace() method replaces only the first occurrence of a specified value.
However, with modern browsers supporting ECMAScript 2021, you can now use the replaceAll() method for a cleaner and simpler approach.
1. Modern Solution: Using String.replaceAll()
If you’re targeting up-to-date browsers or environments that support ES2021+, use the built-in replaceAll() method:
This removes every occurrence of 'abc' from the string.
✅ Simple, safe, and native — no need for regular expressions.
2. Using Regular Expressions with replace()
For older browsers or JavaScript environments that don’t support replaceAll(), you can use a regular expression with the global (g) flag:
The /g flag tells JavaScript to replace all matches, not just the first one.
3. Replacing a Dynamic Value (Stored in a Variable)
If the text to replace is stored in a variable, you can dynamically build a regular expression using the RegExp constructor:
This lets you replace variable substrings — for example, a word entered by a user.
4. Making It Safe: Escaping Special Characters
If your search string may include special regex characters (., *, +, etc.), you should escape them before creating a regular expression.
Here’s a utility function recommended by Mozilla Developer Network (MDN):
This ensures that your find string is treated as literal text, not a pattern.
Example usage:
Summary:
In short:
✅ Use string.replaceAll() for modern projects.
⚙️ Use string.replace(new RegExp(find, 'g'), replace) for legacy support.
Both methods help ensure that every instance of your target substring is replaced across the entire string.