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

JavascriptObject Oriented ProgrammingFront End Technology

/g is one of the regular expressions that make a user task easy. /g searches for a provided word globally. If any word is to be replaced by another word throughout all occurrences then /g comes into the picture. Let's discuss it in a nutshell.

In the following example, we need to replace all the provided blue words with red and we have applied the normal str.replace() method to achieve the task. Since there is no global indication, the first occurrence of the word blue is only changed, leaving the rest of the occurrences constant. Be aware that javascript is case sensitive. 

Example

Live Demo

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

Output

Mr Blue has a red house and a blue car

In the following example, since global indication(/g) is used all the words "blue" are replaced with word red. Make sure that javascript is a case sensitive language.  

Example

Live Demo

<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
raja
Published on 19-Jul-2019 14:25:30
Advertisements