Replace All Instances of a String in JavaScript

Jun 3, 2019

By default, the String#replace() function in JavaScript only replaces the first instance of a substring. Make sure you pass a RegExp with the /g flag set as shown below.

const str = 'A penny saved is a penny earned';

// "A dollar saved is a dollar earned"
str.replace(/penny/g, 'dollar');

// "A dollar saved is a penny earned" - only replaces the first
// instance by default.
str.replace('penny', 'dollar');

Remember JavaScript strings are immutable. When you use replace(), you don't modify the original string.

Replacement Patterns

The String#replace() function has several special character sequences called "replacement patterns". Replacement patterns are useful when you want to replace all substrings that match a regular expression with a string that contains the match.

For example, suppose you wanted to add a # before all numbers in a string. You can use the $& replacement pattern, which inserts the matched substring.

const str = 'My favorite team is 1, everyone else is 2';

// "My favorite team is #1, everyone else is #2"
str.replace(/\d+/g, '#$&');

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials