Replace all occurrences of a string in JavaScript

 by Robin Wieruch
 - Edit this Post

Eventually everyone came across the case that JavaScript's replace function, which is available on a , does only replace one occurrence of the matched term.

const text = 'Hello World';
const newText = text.replace('o', 'ö');
console.log(newText);
// "Hellö World"

Here I want to show you briefly how to replace all occurrences in JavaScript with two different ways. The first way uses a regular expression to find all matches with a global flag:

const text = 'Hello World';
const newText = text.replace(/o/g, 'ö');
console.log(newText);
// "Hellö Wörld"

Without the global flag, the regex would only match one occurrence. An alternative to this is JavaScript's replaceAll function, which is built-in for JavaScript string primitives, but not available for all browsers yet:

const text = 'Hello World';
const newText = text.replaceAll('o', 'ö');
console.log(newText);
// "Hellö Wörld"

While replaceAll isn't fully available yet, you can use the regex version of replaceAll and the global flag g with JavaScript's replace version to replace all occurrences of a string.

Keep reading about 

A JavaScript naming conventions introduction by example -- which gives you the common sense when it comes to naming variables, functions, classes or components in JavaScript. No one is enforcing these…

The article is a short tutorial on how to achieve global state in React without Redux. Creating a global state in React is one of the first signs that you may need Redux (or another state management…

The Road to React

Learn React by building real world applications. No setup configuration. No tooling. Plain React in 200+ pages of learning material. Learn React like 50.000+ readers.

Get it on Amazon.