Replace a String case-insensitive in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 1, 2024
2 min

banner

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

To do a case-insensitive string replacement in JavaScript:

  1. Call the String.replace() method method on the string.
  2. Set the ignore flag on the first argument.
  3. The ignore flag does a case-insensitive search in the string.
index.js
const str = 'HELLO HELLO world'; const replaced = str.replace(/hello/gi, 'bye'); console.log(replaced); // ๐Ÿ‘‰๏ธ bye bye world

replace string case insensitive in javascript

The code for this article is available on GitHub

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:

NameDescription
patternThe pattern to look for in the string. Can be a string or a regular expression.
replacementA string used to replace the substring match by the supplied pattern.

The first argument we passed to the replace() method is a regular expression.

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

index.js
const str = 'HELLO HELLO world'; const replacedOnce = str.replace(/hello/i, 'bye'); console.log(replacedOnce); // ๐Ÿ‘‰๏ธ bye HELLO world

only replacing the first time regex matches case insensitive

The code for this article is available on GitHub

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.

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.

Copyright ยฉ 2024 Borislav Hadzhiev