JavaScript RegExp g: Global Match Explained

The g flag in JavaScript regular expressions enables global matching. When this flag is used, the regular expression engine searches for all occurrences of the pattern within a string, rather than stopping after the first match. This is particularly useful when you need to find and potentially replace multiple instances of a substring.

Purpose of the g Flag

The primary purpose of the g flag is to find all matches of a pattern in a string. Without this flag, RegExp.exec() and String.match() methods only return the first match.

Syntax

The g flag is appended to the end of the regular expression pattern:

const regex = /pattern/g; // Using literal notation
const regex = new RegExp("pattern", "g"); // Using constructor notation

Attributes

The g flag does not have specific attributes. It is a modifier that alters how the regular expression engine searches the string.

Attribute Description
`g` Enables global matching, finding all occurrences of the pattern in the string.

Examples

Here are several examples to demonstrate the use of the g flag.

Basic Usage

This example demonstrates how the g flag finds all occurrences of a pattern.

const str_global = "red blue red green red";
const regex_global = /red/g;
const matches_global = str_global.match(regex_global);

console.log(matches_global);

Output:

[ 'red', 'red', 'red' ]

Without the g flag, match() would only return the first “red”.

Using exec() with the g Flag

The exec() method, when used with the g flag, can be called repeatedly to find subsequent matches.

const str_exec = "color: red; background: red; border: red;";
const regex_exec = /red/g;
let match_exec;

while ((match_exec = regex_exec.exec(str_exec)) !== null) {
  console.log(`Found red at index ${match_exec.index}`);
}

Output:

Found red at index 7
Found red at index 24
Found red at index 39

Each call to exec() advances the regular expression’s lastIndex property to the position after the previous match, allowing it to find the next match in the subsequent call.

Replacing All Occurrences

The g flag is commonly used with the String.replace() method to replace all occurrences of a pattern.

const str_replace = "apple orange apple banana apple";
const regex_replace = /apple/g;
const newStr_replace = str_replace.replace(regex_replace, "mango");

console.log(newStr_replace);

Output:

mango orange mango banana mango

All instances of “apple” are replaced with “mango”.

Ignoring Case with i and Global Match

You can combine the g flag with the i flag for case-insensitive global matching.

const str_ignoreCase = "JavaScript is different from javascript";
const regex_ignoreCase = /javascript/gi;
const matches_ignoreCase = str_ignoreCase.match(regex_ignoreCase);

console.log(matches_ignoreCase);

Output:

[ 'JavaScript', 'javascript' ]

Both “JavaScript” and “javascript” are matched, regardless of case.

Using with Character Classes

Combining the g flag with character classes can be very powerful. For example, finding all vowels in a string:

const str_vowels = "This is a String with multiple vowels";
const regex_vowels = /[aeiou]/gi;
const matches_vowels = str_vowels.match(regex_vowels);

console.log(matches_vowels);

Output:

[ 'i', 'i', 'a', 'i', 'u', 'i', 'e', 'o', 'u', 'i', 'e', 'v', 'o', 'e', 'l', 's' ]

Practical Example: Finding All Email Addresses

This example demonstrates a more practical use case: extracting all email addresses from a block of text.

const text_emails = `
Contact us at [email protected] or [email protected].
For more information, visit [email protected].
`;
const regex_emails = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g;
const emails_emails = text_emails.match(regex_emails);

console.log(emails_emails);

Output:

[ '[email protected]', '[email protected]', '[email protected]' ]

This regular expression finds all valid email addresses in the text.

Use Case Example: Highlighting Search Terms

Let’s create a practical example that demonstrates how to use the g flag to highlight search terms in a block of text dynamically.

<div id="textBlock" style="padding: 20px; border: 1px solid #ddd;">
  This is a sample text block.  You can search for specific words to highlight them.
</div>

<input type="text" id="searchInput" placeholder="Enter search term">
<button id="searchButton">Highlight</button>

<script>
  document.getElementById('searchButton').addEventListener('click', function() {
    const searchTerm = document.getElementById('searchInput').value;
    const textBlock = document.getElementById('textBlock');
    const originalText = textBlock.innerText;

    // Clear previous highlights
    textBlock.innerHTML = originalText;

    if (searchTerm) {
      const regex = new RegExp(searchTerm, 'gi');
      const highlightedText = originalText.replace(regex, '<span style="background-color: yellow;">$&</span>');
      textBlock.innerHTML = highlightedText;
    }
  });
</script>

When the user enters a search term and clicks the “Highlight” button, the script dynamically highlights all occurrences of the search term in the text block.

This example demonstrates several important concepts:

  1. Dynamic Regular Expression: Using new RegExp() to create a regular expression from user input.
  2. Global and Case-Insensitive Matching: Using the gi flags to find all matches regardless of case.
  3. Replacement with Matched Text: Using $& in the replace() method to insert the matched text within the highlight span.
  4. DOM Manipulation: Dynamically updating the HTML content of the text block to display the highlighted text.

Browser Support

The g flag is widely supported across all modern web browsers.

Conclusion

The g flag in JavaScript regular expressions is essential for performing global matches, allowing you to find all occurrences of a pattern within a string. When combined with other flags and methods, it becomes a powerful tool for tasks like search, replace, and data extraction. Understanding and utilizing the g flag effectively will significantly enhance your ability to manipulate and analyze text using regular expressions in JavaScript. 🚀