How to replace all occurrences in a string in JavaScript
Replacing all occurrences of substrings is essential for data cleaning, text processing, template rendering, and implementing features like find-and-replace functionality in JavaScript applications.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented global string replacement in components like text editors, data formatters, and content processors where comprehensive text transformation is required.
From my extensive expertise, the most modern and straightforward solution is using the ES2021 replaceAll()
method, which handles all instances in a single operation.
This approach is intuitive, efficient, and eliminates the need for complex regular expressions or iterative replacements.
Use the replaceAll()
method to replace every occurrence of a substring in a string.
const text = 'hello world, hello universe'
const updated = text.replaceAll('hello', 'hi')
// Result: 'hi world, hi universe'
The replaceAll()
method searches the entire string for every occurrence of the first parameter and replaces each instance with the second parameter. In this example, text.replaceAll('hello', 'hi')
finds both instances of ‘hello’ and replaces them with ‘hi’, resulting in ‘hi world, hi universe’. Unlike the regular replace()
method which only replaces the first occurrence, replaceAll()
handles every match in a single call. The method is case-sensitive and returns a new string without modifying the original.
Best Practice Note:
This is the same approach we use in CoreUI components for processing template strings, cleaning user input, and formatting display text across our component ecosystem.
For older browser support, use the global regex pattern: text.replace(/hello/g, 'hi')
. For case-insensitive replacement, combine with regex: text.replaceAll(/hello/gi, 'hi')
. The replaceAll()
method is supported in modern browsers (ES2021+) and provides cleaner syntax than regex alternatives.