Regex Flags in JavaScript: g, i, m, s, u, y Explained
Learn what JavaScript regex flags do, when to combine g/i/m/s/u, and common mistakes that break multiline and Unicode matching.
Quick answer
Regex flags change matching behavior: g finds all matches, i ignores case, m treats lines separately for anchors, s lets dot match newlines, u enables Unicode properties, y matches only at lastIndex.
Key takeaways
- ›Missing g is the most common reason replace only changes the first match.
- ›Use m for log lines and s when dot must cross newlines.
- ›Always add u when matching emoji or non-Latin scripts.
- ›Reset lastIndex when reusing global regex objects.
Apply this guide with the Regex Tester
Open Regex TesterRegex flags change how a pattern matches — the same pattern with different flags can pass or fail on identical input. Use the Regex Tester to toggle flags and see matches update in real time.
What regex flags do
Flags are modifiers appended after the closing / in JavaScript literal syntax, or passed as the second argument to new RegExp(pattern, flags).
/pattern/flags
// ^^^^^ gimsuvy in JavaScriptWithout the right flags, valid patterns look broken — especially for multiline logs, case-insensitive validation, and Unicode property escapes.
The g flag (global)
Global — find all matches, not just the first.
const text = 'id-1 id-2 id-3';
text.match(/id-\d/); // ['id-1'] — first only
text.match(/id-\d/g); // ['id-1', 'id-2', 'id-3']Pitfall: String.prototype.match with g returns an array of matches without capture groups. Use matchAll when you need groups from every match.
[...text.matchAll(/id-(\d)/g)].map((m) => m[1]); // ['1', '2', '3']The i flag (ignore case)
Case insensitive matching.
/ERROR/i.test('error line 42'); // trueUse for user-facing validation (emails, slugs) where case should not matter. Do not rely on i alone for security filters — normalize input separately when needed.
The m flag (multiline)
Multiline — ^ and $ match line boundaries, not only string start/end.
const log = 'OK first\nERROR second\nOK third';
log.match(/^ERROR/m); // matches 'ERROR' at line startEssential for parsing stack traces, config files, and linter output line by line.
The s flag (dotall)
Dotall — . matches newline characters (\n, \r).
const block = 'start\nmiddle\nend';
/start.*end/s.test(block); // true — dot crosses newlinesWithout s, . stops at the first newline. Combine with m carefully when anchoring lines vs blocks.
The u flag (unicode)
Unicode — enables \u{...} code points and Unicode property escapes \p{...}.
/\p{Script=Greek}/u.test('δ'); // trueRequired for emoji, combining marks, and non-Latin scripts. Without u, surrogate pairs and properties behave incorrectly.
The y flag (sticky)
Sticky — match only at lastIndex (advanced tokenizer use).
const re = /\w+/y;
re.lastIndex = 0;
re.exec('abc def'); // ['abc'] — stops at space, lastIndex = 3Rare in application code; useful for manual parsers. Misuse causes silent non-matches when lastIndex is wrong.
Flag combinations that matter in practice
| Task | Typical flags |
|---|---|
| Extract all emails in a blob | gi |
| Validate entire string is lowercase slug | anchor + i optional |
| Parse multiline log levels | m |
| Match JSON-like block across lines | s (with caution) |
| Match international names | u |
| Replace all occurrences | g with replaceAll or g + replace |
// Validate full string (not substring) — use anchors
/^[a-z0-9-]+$/.test(userSlug);Common flag mistakes
| Mistake | Symptom | Fix |
|---|---|---|
Forgot g in replace | Only first match replaced | Add g or use replaceAll |
Forgot m on multiline input | ^ only matches file start | Add m |
Forgot u for emoji | Surrogate half-matches | Add u |
Greedy .* without s | Stops at first newline | Add s or use [\s\S] |
g + test() in a loop | Alternating true/false | Reset lastIndex or avoid g with test |
const re = /foo/g;
re.test('foo'); // true — lastIndex advanced
re.test('foo'); // false — starts mid-string
re.lastIndex = 0; // reset when reusing global regexHow to use ByteToolBox Regex Tester
- Open Regex Tester
- Enter pattern and test string
- Toggle g, i, m (and others your engine supports)
- Inspect match list, groups, and highlights
- Copy the working pattern into your codebase
Test edge cases: empty string, Unicode emoji, Windows \r\n newlines.
See also: Mastering Regular Expressions for pattern syntax depth.
Related tools
- Regex Tester — live flag toggling and match inspection
- JSON Formatter — validate JSON extracted by regex before parsing
Try Regex Tester
Debug your next validation regex with flags enabled in the Regex Tester.
Related tools
Related guides
Mastering Regular Expressions: A Developer's Guide
From basic patterns to advanced techniques, learn how to write efficient and maintainable regular expressions.
JSONHow to Find and Fix Invalid JSON With Real Error Examples
Fix invalid JSON with real examples: trailing commas, missing quotes, bad escaping, comments, and mismatched brackets.