A regular expression is a compact pattern for matching, searching, or manipulating text. In JavaScript, `/pattern/` creates one. The Unicode trap is that, without the `u` flag, a pattern matches UTF-16 code units: a character represented by a surrogate pair can be split across matches. section 2.1.2
One visible symbol, two matching units
With `const str = '😀ABC'`, `/^./.exec(str)` matches only the first code unit of the emoji. `/^.{3}/.exec(str)` consumes both units of the emoji and `A`. Add `u`: `/^./u` matches the emoji as one unit of the pattern, while `/^.{3}/u` matches `😀AB`. section 2.1.2
Use `u` for patterns that may encounter characters outside basic ASCII, especially when matching emoji, writing Unicode ranges, or using property escapes such as `\p{Emoji}`. It addresses surrogate-pair matching; it does not replace normalization before validating or comparing identifiers that may have different Unicode representations. section 2.1.2 section 2.3
Listing 2.3 Surprising behavior with Unicode and Regular Expressions
// Without the 'u' flag, regex treats surrogate pairs incorrectly
const str = '😀ABC'; #A
// Default behavior - sees surrogate pairs as two characters
/^./.exec(str); #B
/^.{3}/.exec(str); #C
// With 'u' flag - Unicode-aware matching
/^./u.exec(str); #D
/^.{3}/u.exec(str); #E
// Character classes need 'u' flag for Unicode ranges
/[😀-😎]/.test('😀'); #F
/[😀-😎]/u.test('😀'); #G
// Unicode property escapes require 'u' flag
/\p{Emoji}/u.test("😀"); #H
/\p{Script=Greek}/u.test("α"); #ICompare anchored matches, an emoji range, and Unicode property escapes with and without the `u` flag. section 2.1.2































