How do you replace all occurrences of a string?

Until the last few years, working with string replacement in JavaScript code required special tricks. That is no longer the case for major browsers.

To replace all occurrences of a string within another string you can use the method .replaceAll:

const source = 'This string replaces two occurrences of the substring replace';

const replaced = source.replaceAll('replace', 'keep');

// Outputs: This string keeps two occurrences of the substring keep

The .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 .replaceAll:

  1. Using regular expressions with g flag:
const source = 'My favorite color of all colors is orange';

const replaced = source.replaceAll(/color/g, 'fruit');

// Outputs: My favorite fruit of all fruits is orange
  1. Using .join/.split:
const source = 'life sweet life';

const replaced = source.split('life').join('home');

// 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!