Regex Flags Explained: g, i, m, s
What Are Regex Flags?
Regex flags (also called modifiers) change how a pattern matches text. They're added after the
closing delimiter in a regex pattern, like /pattern/gi.
Each flag modifies specific behavior — whether to find all matches, ignore case, or treat the pattern differently in multi-line text.
The Four Common Flags
Without g, the regex stops after the first match. With g, it finds
every match in the string.
Example:
// Without g
"cat dog cat".match(/cat/)
// Returns: ["cat"] (first match only)
// With g
"cat dog cat".match(/cat/g)
// Returns: ["cat", "cat"] (all matches)
When to use: Search and replace operations, finding all occurrences, counting matches.
Makes the pattern match both uppercase and lowercase letters. "A" matches "a", "B" matches "b", and so on.
Example:
// Without i
"Hello HELLO hello".match(/hello/)
// Returns: ["hello"] (exact case match only)
// With i
"Hello HELLO hello".match(/hello/gi)
// Returns: ["Hello", "HELLO", "hello"]
When to use: User input validation, searching text where case varies, email/URL matching.
Changes how ^ (start) and $ (end) anchors work. Without
m, they match the start and end of the entire string. With m, they
match the start and end of each line.
Example:
const text = "first line\nsecond line";
// Without m
text.match(/^second/)
// Returns: null (^ only matches string start)
// With m
text.match(/^second/m)
// Returns: ["second"] (^ matches line start)
When to use: Processing multi-line text, validating each line separately, log file parsing.
By default, the dot . matches any character except newlines. With
s, it also matches newline characters, allowing patterns to span multiple
lines.
Example:
const text = "start\nmiddle\nend";
// Without s
text.match(/start.*end/)
// Returns: null (. doesn't match \n)
// With s
text.match(/start.*end/s)
// Returns: ["start\nmiddle\nend"]
When to use: Matching content across lines, parsing HTML/XML blocks, multi-line string extraction.
Combining Flags
Flags can be combined in any order. Common combinations:
gi— Find all matches, case insensitive (most common for search)gm— Find all matches in multi-line textgms— Full multi-line mode with dot matching newlinesgims— All flags enabled
Flag Behavior Summary
Flag Affects Default Behavior
──── ─────── ────────────────
g Match iteration Stops after first match
i Case sensitivity Case-sensitive matching
m Anchor behavior ^ $ match string boundaries
s Dot character . doesn't match newlines
Frequently Asked Questions
/pattern/gi and /pattern/ig are
identical. Flags can be in any order./pattern/gi. In constructor:
new RegExp("pattern", "gi"). Both work the same way.g, replace() only replaces the
first match. With g, it replaces all matches.u (unicode) for full Unicode
support and y (sticky) for matching only at the lastIndex position. These
are less commonly used.