Replace a String case insensitive in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 04 20211 min read

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
index.js
// 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:

index.js
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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee