Replacing All String Instances With replaceAll()

javascript
Published on December 26, 2020

All instances of a given string can be replaced by using the replaceAll() method.

replaceAll() is similar to the replace() method which replaces only the first instance of the string. However replaceAll() replaces all instances.

let str = "this is a sample sentence";

// replace each space with dash
str = str.replaceAll(" ", "-");

// "this-is-a-sample-sentence"
console.log(str);

The return value of replaceAll() is the new replaced string. The original string is left unchanged.

Browser Support : replaceAll() is supported by all modern browsers — Chrome, Edge, Firefox & Safari.

In this Tutorial