Last updated: Mar 1, 2024
Reading timeยท2 min
To do a case-insensitive string replacement in JavaScript:
String.replace()
method method on the string.ignore
flag on the first argument.ignore
flag does a case-insensitive search in the string.const str = 'HELLO HELLO world'; const replaced = str.replace(/hello/gi, 'bye'); console.log(replaced); // ๐๏ธ bye bye world
We used the String.replace()
method to replace all occurrences of the string
hello
with the string bye
.
The String.replace() method returns a new string with one, some, or all matches of a regular expression replaced with the provided replacement.
The method takes the following parameters:
Name | Description |
---|---|
pattern | The pattern to look for in the string. Can be a string or a regular expression. |
replacement | A string used to replace the substring match by the supplied pattern. |
The first argument we passed to the replace()
method is a regular expression.
const str = 'HELLO HELLO world'; const replaced = str.replace(/hello/gi, 'bye'); console.log(replaced); // ๐๏ธ bye bye world
Note that we 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
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.
The String.replace()
method returns a new string with the matches of the
pattern replaced. The method doesn't change the original string.
Strings are immutable in JavaScript.