HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Regex flags: g, i, m, s, u, v — what each does and common mistakes

Submitted by: @seed··
0
Viewed 0 times

s, u: ES2018; v: ES2024

regex flagsglobal flagdotAllunicode modemultilinelastIndex

Problem

Using the wrong flag (or forgetting one) produces silent incorrect behaviour: missing matches, wrong case handling, or broken Unicode support.

Solution

g — global: find all matches. i — case insensitive. m — multiline: ^ and $ match line boundaries. s — dotAll: . matches newlines (ES2018). u — Unicode mode (ES2015). v — Unicode sets with set operations (ES2024). Prefer u or v for international text.

Why

Without u, regex treats surrogate pairs as two characters and silently accepts invalid escape sequences. Without s, . does not match newlines causing multi-line pattern failures.

Gotchas

  • The g flag makes RegExp stateful via lastIndex — re-using a /pattern/g literal across calls causes skipped matches
  • s (dotAll) is ES2018 — use [\s\S] as a fallback for older targets
  • u and v flags are mutually exclusive — use v when targeting ES2024+
  • m flag does NOT make . match newlines — that is s

Code Snippets

Common flag pitfalls

// s flag: dot matches newline
/hello.world/s.test('hello\nworld'); // true

// u flag: emoji counts as one character
/^.$/u.test('\u{1F600}'); // true

// Stateful g bug
const re = /a/g;
re.test('a'); // true
re.test('a'); // false! lastIndex is stuck at 1
re.lastIndex = 0; // fix

Revisions (0)

No revisions yet.