Open In App

JavaScript RegExp g Modifier

Last Updated : 06 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The g (global) modifier in JavaScript regular expressions is used to perform a global search. It ensures the pattern is matched multiple times throughout the entire string, rather than stopping at the first match.

let regex = /cat/g;
let str = "cat, caterpillar, catch a cat";
let matches = str.match(regex);
console.log(matches); 

Output
[ 'cat', 'cat', 'cat', 'cat' ]

The g modifier finds all occurrences of “cat” in the string, even if they appear multiple times.

Syntax:

/pattern/g

Key Points

  • Global Search: Finds all matches in the string, not just the first.
  • Combination: Can be combined with other flags like i (case-insensitive) and m (multiline).
  • Match Iteration: Useful for iterating over all matches using methods like match(), exec(), or loops.

Real-World Examples

1. Finding All Matches

let regex = /dog/g;
let str = "dog, doggy, dogs are friends";
let matches = str.match(regex);
console.log(matches); 

Output
[ 'dog', 'dog', 'dog' ]

Here, the g modifier ensures all matches of “dog” are found in the string.

2. Counting Word Occurrences

let str = "apple orange apple banana apple";
let regex = /apple/g;
let count = (str.match(regex) || []).length;
console.log(count); 

Output
3

Using the g modifier with match(), we can count how many times “apple” appears.

3. Replacing All Matches

let str = "foo bar foo baz foo";
let regex = /foo/g;
let result = str.replace(regex, "qux");
console.log(result); 

Output
qux bar qux baz qux

The g modifier ensures all occurrences of “foo” are replaced with “qux”.

4. Iterating Over Matches

let regex = /\d+/g;
let str = "The price is 20 dollars and 30 cents.";
let match;
while ((match = regex.exec(str)) !== null) {
    console.log(`Found: ${match[0]} at index ${match.index}`);
}

Output
Found: 20 at index 13
Found: 30 at index 28

The g modifier with exec() allows iterating over all numeric matches in the string.

5. Case-Insensitive Global Search

let regex = /hello/gi;
let str = "Hello, HELLO, hello";
let matches = str.match(regex);
console.log(matches); 

Output
[ 'Hello', 'HELLO', 'hello' ]

Combining g with i makes the search case-insensitive while finding all matches.

When Not to Use the g Modifier

If you only need the first match, do not use g. For example, str.match() without g returns only the first match as an array.

let str = "repeat repeat repeat";
console.log(str.match(/repeat/)); 

Output
[
  'repeat',
  index: 0,
  input: 'repeat repeat repeat',
  groups: undefined
]

When using test() in loops, the g modifier can cause unexpected results due to its effect on the lastIndex property.

Why Use the g Modifier?

  • Comprehensive Matching: Ensures no match is missed in the target string.
  • Text Analysis: Useful for tasks like word frequency analysis or log parsing.
  • String Manipulation: Ideal for global replacements and transformations.

Conclusion

The g modifier is essential for working with patterns that occur multiple times in a string, making it a powerful tool for developers in text processing and manipulation.

Recommended Links:



Next Article

Similar Reads

three90RightbarBannerImg