How to Use Global Flag in Regex JavaScript: Simple Guide
In JavaScript, add the
g flag to a regular expression to search for all matches in a string instead of stopping at the first match. For example, /pattern/g enables global matching, allowing methods like match() or replace() to work on every occurrence.Syntax
The global flag g is added after the closing slash of a regular expression to enable searching for all matches in a string.
/pattern/g: Thepatternis the text or pattern you want to find.g: The global flag tells JavaScript to find all matches, not just the first.
javascript
/pattern/g
Example
This example shows how the global flag finds all occurrences of the word "cat" in a string.
javascript
const text = "cat bat cat rat cat"; const regexWithoutG = /cat/; const regexWithG = /cat/g; const firstMatch = text.match(regexWithoutG); const allMatches = text.match(regexWithG); console.log("First match without global flag:", firstMatch); console.log("All matches with global flag:", allMatches);
Output
First match without global flag: [ 'cat', index: 0, input: 'cat bat cat rat cat', groups: undefined ]
All matches with global flag: [ 'cat', 'cat', 'cat' ]
Common Pitfalls
Without the global flag, regex methods like match() return only the first match. Forgetting g can cause unexpected results when you want all matches.
Also, when using the global flag with exec(), the regex object keeps track of the last index, so repeated calls find successive matches.
javascript
const text = "dog dog dog"; const regex = /dog/g; console.log(regex.exec(text)); // First match console.log(regex.exec(text)); // Second match console.log(regex.exec(text)); // Third match console.log(regex.exec(text)); // null (no more matches)
Output
[ 'dog', index: 0, input: 'dog dog dog', groups: undefined ]
[ 'dog', index: 4, input: 'dog dog dog', groups: undefined ]
[ 'dog', index: 8, input: 'dog dog dog', groups: undefined ]
null
Quick Reference
| Flag | Meaning | Effect |
|---|---|---|
| g | Global | Find all matches, not just the first |
| i | Ignore case | Match letters regardless of case |
| m | Multiline | Make ^ and $ match start/end of lines |
Key Takeaways
Add the 'g' flag to regex to find all matches in a string.
Without 'g', methods like match() return only the first match.
Using 'g' with exec() lets you find matches one by one.
Remember to reset regex lastIndex or create a new regex when reusing with 'g'.
Combine 'g' with other flags like 'i' for case-insensitive global search.