C.W.K.
Stream
Lesson 06 of 10 · published

JavaScript Flags Deep Dive

~8 min · javascript, flags

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

The eight flags

JavaScript regex flags as of ES2024:

  • i — case-insensitive
  • g — global (find all matches; enables matchAll and replaceAll)
  • m — multiline (^ and $ match line boundaries)
  • s — dotAll (. matches newlines)
  • u — Unicode (treats pattern and string as Unicode code points)
  • y — sticky (matches starting at lastIndex only)
  • d — has indices (match objects include start/end offsets for groups; ES2022+)
  • v — Unicode sets (extended Unicode features; ES2024)

Combining flags

Flags are concatenated in any order: /pattern/gimsu. Order doesn't matter; duplicates are an error.

The Unicode flag (/u)

Without /u, JavaScript treats astral plane characters (emoji, rare Asian scripts) as surrogate pairs — one character looks like two to the regex. With /u, characters are treated as Unicode code points.

Always use /u when matching Unicode text. It enables \p{...} Unicode category escapes and makes . match a single emoji as one unit.

The sticky flag (/y)

/y is /g's pickier cousin: it matches ONLY at lastIndex. Useful for tokenizers that consume input piece by piece without skipping junk between matches.

Code

JavaScript flags in action·js
// Case-insensitive
'Hello'.match(/hello/i)  // ['Hello']

// Multiline — ^/$ per line
const log = 'line1\nERROR\nline3';
log.match(/^ERROR$/m)  // ['ERROR']
log.match(/^ERROR$/)   // null (whole string isn't ERROR)

// dotAll — . matches newline
'a\nb'.match(/a.b/s)  // ['a\nb']
'a\nb'.match(/a.b/)   // null

// Unicode — emoji as one char
'\u{1F4A1}'.match(/.+/u)   // ['💡']
'\u{1F4A1}'.length         // 2 (surrogate pair without u flag)

// Unicode property escapes (require /u)
'안녕 hello'.match(/\p{Script=Hangul}+/gu)
// ['안녕']

// Indices flag (/d) — exact positions
const m = 'hello world'.match(/world/d);
m.indices  // [[6, 11]]

External links

Exercise

Try matching the emoji 💡 (U+1F4A1) with /^.$/ and with /^.$/u in the JavaScript console. The first should fail, the second succeed. That's the surrogate pair issue the /u flag fixes.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.