Replacing All String Instances With replaceAll()

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"

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.

Related Tutorials
How to Trim Strings in Javascript
How to Pad Strings in Javascript
Repeat a String for Multiple Times in Javascript
Creating Multi-line Strings in Javascript with Template Literals
Checking for a Sub-String in Javascript - All Possible Cases
Loading Comments