Computer >> Computer tutorials >  >> Programming >> Javascript

What is the importance of '/i' flag in JavaScript?


Javascript is a case sensitive language. When we try to replace a word with another word, we need to check the case of the letters whether capital or small. For a single word, the process of checking is easy but take a scenario in which there are more of number words to check. So to make this process easy "/i" comes into the picture. It replaces the word with another word irrespective of the case. 

Example

In the following example, we need to replace all the occurrences of the word blue with red. But since, one of the occurrences is in capital case except that, every other occurrence of the word "blue" is changed to red

<html>
<body>
<script>
   var str = "Mr Blue has a blue house and a blue car";
   var res = str.replace(/blue/g, "red");
   document.write(res);
</script>
</body>
</html>

Output

Mr Blue has a red house and a red car

When "/i" flag is used, irrespective of the case of the words, every word will be replaced with the provided word.

Example

In the following example, since "/i" flag is used, irrespective of the case of the letters all occurrences of the word blue are changed to red.

<html>
<body>
<script>
   var str = "Mr Blue has a blue house and a blue car";
   var res = str.replace(/blue/ig, "red");
   document.write(res);
</script>
</body>
</html>

Output

Mr red has a red house and a red car