JavaScript RegExp g Modifier (original) (raw)
Last Updated : 06 Dec, 2024
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.
JavaScript `
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
JavaScript `
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
JavaScript `
let str = "apple orange apple banana apple"; let regex = /apple/g; let count = (str.match(regex) || []).length; console.log(count);
`
Using the g modifier with match(), we can count how many times "apple" appears.
3. Replacing All Matches
JavaScript `
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
JavaScript ``
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: <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>m</mi><mi>a</mi><mi>t</mi><mi>c</mi><mi>h</mi><mo stretchy="false">[</mo><mn>0</mn><mo stretchy="false">]</mo></mrow><mi>a</mi><mi>t</mi><mi>i</mi><mi>n</mi><mi>d</mi><mi>e</mi><mi>x</mi></mrow><annotation encoding="application/x-tex">{match[0]} at index </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord mathnormal">ma</span><span class="mord mathnormal">t</span><span class="mord mathnormal">c</span><span class="mord mathnormal">h</span><span class="mopen">[</span><span class="mord">0</span><span class="mclose">]</span></span><span class="mord mathnormal">a</span><span class="mord mathnormal">t</span><span class="mord mathnormal">in</span><span class="mord mathnormal">d</span><span class="mord mathnormal">e</span><span class="mord mathnormal">x</span></span></span></span>{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
JavaScript `
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.
JavaScript `
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.