Categories
JavaScript Answers

How to do case insensitive replace all with JavaScript?

Spread the love

Sometimes, we want to do case insensitive replace all with JavaScript.

In this article, we’ll look at how to do case insensitive replace all with JavaScript.

How to do case insensitive replace all with JavaScript?

To do case insensitive replace all with JavaScript, we can use a regex.

For instance, we write

const searchMask = "is";
const regEx = new RegExp(searchMask, "ig");
const replaceMask = "as";

const result = "This iS IIS".replace(regEx, replaceMask);

to create a regex with the RegExp constructor.

searchMask is the pattern we’re looking to replace.

i makes the regex match in a case insensitive manner.

g makes the regex search for all matches of the pattern.

Then we call replace with regEx and the replaceMask that we want to replace the matched strings with.

Conclusion

To do case insensitive replace all with JavaScript, we can use a regex.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *