Last updated: Oct 4, 2021
Photo from Unsplash
ignoreflag on the first parameter
// Supported in IE 6-11 const str = 'HELLO HELLO world'; const replaced = str.replace(/hello/gi, 'bye'); console.log(replaced); // 👉️ bye bye world
In the code snippet, we've used the
method to replace all occurrences of the string
hello with the string
String.replacefunction is a regular expression that has to match the string we want to replace.
Note that we've set the
g flags on the regular expression.
i flag stands for
ignore and does a case insensitive search in string.
g flag stands for
global and replaces all occurrences of the matched
If you only want to do a case insensitive replacement the first time the regular
expression matches the string, remove the
const str = 'HELLO HELLO world'; const replacedOnce = str.replace(/hello/i, 'bye'); console.log(replacedOnce); // 👉️ bye HELLO world
In the code example the regular expression is matched in the string two times,
however we haven't set the
g flag so only the first match is replaced.