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

The /g flag in JavaScript regular expressions stands for "global" and is essential for finding all matches in a string rather than stopping after the first match. Without this flag, regex methods will only find the first occurrence of a pattern.

Understanding Regular Expressions

Regular expressions are patterns used to match character combinations in strings. They can be created in two ways:

  • Literal notation: Uses forward slashes with optional flags after the second slash (e.g., /pattern/g). This is preferred when the pattern remains constant.

  • Constructor function: Uses new RegExp("pattern", "flags"). This is useful when the pattern needs to be built dynamically during execution.

Syntax

/regexp/g

OR

new RegExp("regexp", "g")

Example 1: Replacing Multiple Matches

This example demonstrates how the /g flag removes all digits from a string, not just the first one:

<!DOCTYPE html>
<html>
<head>
   <title>Global Flag Example</title>
</head>
<body>
   <script>
      let strName = "Tutorial5point1 ha3s 2many digits9";
      let regex = /[\d]/g;

      document.write("Original: " + strName + "<br>");
      document.write("Without digits: " + strName.replace(regex, ""));
   </script>
</body>
</html>

Example 2: Finding All Matches

The match() method with the /g flag returns an array of all matches found in the string:

<!DOCTYPE html>
<html>
<head>
   <title>Match All Numbers</title>
</head>
<body>
   <div id="result"></div>
   <script>
      let regularExp = /\d+/g;
      let strAge = "John: 42, Mike: 44, Sarah: 38";

      document.getElementById("result").innerHTML = strAge.match(regularExp);
   </script>
</body>
</html>

Comparison: With and Without /g Flag

Without /g Flag With /g Flag
Finds only the first match Finds all matches in the string
"a1b2c3".replace(/\d/, "X") ? "aXb2c3" "a1b2c3".replace(/\d/g, "X") ? "aXbXcX"

Example 3: Using exec() with Global Flag

The exec() method with the /g flag can be used in loops to find all email addresses in text:

<!DOCTYPE html>
<html>
<head>
   <title>Extract Email Addresses</title>
</head>
<body>
   <script>
      var webPage = "Contact: admin@test.org, support@email.com, info@site.net";
      var regExp = /[a-zA-Z]+@[a-zA-Z]+\.[a-zA-Z]+/g;
      var match;
      
      document.write("Found email addresses:<br>");
      while ((match = regExp.exec(webPage)) !== null) {
         document.write(match[0] + "<br>");
      }
   </script>
</body>
</html>

Conclusion

The /g flag is crucial for global pattern matching in JavaScript. It ensures that regex operations find all occurrences of a pattern rather than stopping at the first match, making it essential for comprehensive text processing tasks.

Updated on: 2026-03-15T23:18:59+05:30

660 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements