Performing Global Replacement Within Javascript Strings | Task

Ole Ersoy
May - 01  -  1 min

Scenario

We have the string boo the foo boo the foo. And we want to replace all occurences of boo with pity.

Approach

Note that for result1 we use RegExp to create the regular expression, since this allows us to pass in the BOO_LITERAL. The second argument g means that we should perform the replacement globally.

const BOO_LITERAL = `boo`;
const r = `boo the foo boo the foo`;
const result1 = r.replace(new RegExp(BOO_LITERAL, "g"), "pity");
const result2 = r.replace(/boo/g, "pity");

Demo