How to replace all ocurrences of a string in Javascript? Lets see 2 easy ways with replace() and split() with join() methods

How to replace all ocurrences of a string in Javascript?

In this article we will take a look of how to proper replace all occurrences of a string in plain JavaScript, from Regex with the replace() method to other approach with split() and join() methods

Replace method

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. This pattern can be a RegExp or a string, and the replacement can be a string or a function to be called for each match.

Note: If pattern is a string, only the first occurrence will be replaced and is case sensitive.

Basic:

const text = 'Hello World!';

console.log(text.replace('Hello', ''));
// expected output: " World!"

Case Sensitive:

const text = 'Hello World!';

console.log(text.replace('hello', ''));
// expected output: "Hello World!"

Multiple Ocurrences:

const text = 'Hello World! Hello';

console.log(text.replace('Hello', ''));
// expected output: " World! Hello"

So, if we want to replace all the ocurrences we have to use a RegExp

const text = 'Apples are round, and apples are juicy.';

const regex = /apples/g;

console.log(text.replace(regex, 'pears'));
// expected output: "Apples are round, and pears are juicy."

To perfom case insensitive replacement, use the i option in the regex:

const text = 'Apples are round, and apples are juicy.';

const regex = /apples/gi;

console.log(text.replace(regex, 'pears'));
// expected output: "pears are round, and pears are juicy."

for more info about take a look at RegExp in MDN


Split & Join methods

An alternative solution is using two JavaScript functions split() from String and join() from Array, albeit slower than the regex. With the first split() we will used to truncate a string when it finds a pattern, like in replace() method this pattern can be a RegExp or a string that is case sensitive, and returns an array with the tokens, after that we use join() with the tokens to return a new string

const text = 'pears are round, and pears are juicy.';

console.log(text.split('pears').join('apples'));
// expected output: "apples are round, and apples are juicy."

for more info about split or join