Course contentsShow
← JavaScript
Lesson 1726 of 2,72336. Regular ExpressionsFree lesson

Unicode Mode with 'u'

Enabling proper Unicode handling for astral plane characters and Unicode property escapes.

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:

  1. Treats astral plane characters as single units (not split surrogate pairs)
  2. Enables Unicode property escapes like \p{Emoji} or \p{Letter}
  3. Makes . match any single Unicode code point correctly
  4. 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.