Unicode Mode with 'u'
You'll learn how to enable full Unicode support in regular expressions so they correctly handle emoji, non-Latin scripts, and special characters.
The Problem with Default Regex
By default, JavaScript regular expressions treat characters using UTF-16 code units, not true Unicode code points. This causes problems with astral plane characters—characters that require two UTF-16 code units to represent, like emoji (😀), certain Chinese characters, or mathematical symbols (𝟙).
Without the u flag, the dot metacharacter and character classes can split these characters in half, treating them as two separate units instead of one logical character.
What the 'u' Flag Does
The u flag puts your regex into Unicode mode, which:
- Treats astral plane characters as single units (not split surrogate pairs)
- Enables Unicode property escapes like
\p{Emoji}or\p{Letter} - Makes
.match any single Unicode code point correctly - Enforces stricter, more predictable escaping rules
// Without 'u': treats emoji as TWO units
/^.{1}$/.test('😀'); // false (splits into surrogates)
// With 'u': treats emoji as ONE character
/^.{1}$/u.test('😀'); // true (correct behavior!)
// Unicode property escapes (only work with 'u')
/\p{Emoji}/u.test('😀'); // true
/\p{Letter}/u.test('A'); // true
Think of the u flag as putting on "Unicode glasses"—suddenly your regex sees the actual characters people use, not just the technical encoding underneath.
Key Takeaway: Always use the u flag when working with international text, emoji, or when you need accurate character-based matching instead of code-unit-based matching.