To replace all occurrences of a string within another string you can use the method
const source = 'This string replaces two occurrences of the substring replace'; const replaced = source.replaceAll('replace', 'keep'); console.log(replaced); // Outputs: This string keeps two occurrences of the substring keep
.replaceAll method is available in all major browsers since Firefox 77, Chrome 85, and Safari 13.1.
For historical reasons, the string method
.replace only replaces the first occurrence when used with a string matcher.
However, there are also some alternative tricks to
- Using regular expressions with
const source = 'My favorite color of all colors is orange'; const replaced = source.replaceAll(/color/g, 'fruit'); console.log(replaced); // Outputs: My favorite fruit of all fruits is orange
const source = 'life sweet life'; const replaced = source.split('life').join('home'); console.log(replaced); // Outputs: home sweet home
These are practical if you ever need to work with legacy browsers like IE or old versions of Firefox and Chrome.
Good luck with your replacement adventures!