Replace a String case insensitive in JavaScript


Borislav Hadzhiev

Last updated: Oct 4, 2021


Photo from Unsplash

Replace a String case insensitive in JavaScript - String.replace #

To do a case insensitive string replacement in JavaScript:

  1. Call the String.replace method
  2. Set the ignore 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.

The first parameter we passed to the 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.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.