Borislav Hadzhiev
Mon Oct 04 2021·2 min read
Photo by Persnickety Prints
To do a case insensitive string replacement in JavaScript:
String.replace
methodignore
flag 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
String.replace
method to replace all occurrences of the string hello
with the string bye
.
String.replace
function is a regular expression that has to match the string we want to replace.Note that we've set the i
and g
flags on the regular expression.
The i
flag stands for ignore
and does a case insensitive search in string.
The g
flag stands for global
and replaces all occurrences of the matched
string.
If you only want to do a case insensitive replacement the first time the regular
expression matches the string, remove the g
flag:
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.