Unicode code points and the u flag

Intermediate Β· 16 min

Why /^.$/ rejects a single emoji in JavaScript, how UTF-16 code units differ from code points, and what the u flag and \u{...} change.

Before thisCharacter classesThe dot and newlinesDotall, sticky and Unicode flags

JSConf Β· 25 min Β· from 1:21

Unicode code points and the u flag

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by JSConfReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A JavaScript string is a sequence of UTF-16 code units. A character outside the Basic Multilingual Plane, such as an emoji, takes two units, so its length is 2.
  • Without the u flag, a regex reads those units one at a time. The dot, a character class and a quantifier can each see half an emoji.
  • With the u flag, the pattern and the input are read as code points. /^.$/u matches one emoji, and [πŸ˜€πŸ˜] is a two-member class again.
  • \u{1F600} writes a code point by number, and it only works with u. Without u it means the letter u repeated 1F600 times, which is not what you wanted.
  • u also makes the syntax stricter: an escape like \- that means nothing is a SyntaxError. Python's re already works on code points, so it needs no such flag.

The emoji that counted as two

You write a validator for a username field: exactly one character, any character. /^.$/ looks right. A user types πŸ˜€ and the form rejects it. Nothing is wrong with your pattern. The trouble is that JavaScript and the regex engine disagree with you about what β€œone character” means.

I ran this on Node 26:

const s = "πŸ˜€";
s.length            // 2
[...s].length       // 1
/^.$/.test(s)       // false
/^.$/u.test(s)      // true

The string has length 2, but spreading it into an array gives 1 element. Both numbers are correct. They count different things.

Code points and code units

Unicode assigns every character a number, its code point. πŸ˜€ is U+1F600. That is a text-level idea, independent of how bytes are stored.

JavaScript stores strings as UTF-16 code units, each 16 bits. A code point up to U+FFFF fits in one unit. Anything above that, an emoji or a rare CJK character, does not fit, so UTF-16 splits it into two units called a surrogate pair. I asked for the raw pieces:

s.charCodeAt(0).toString(16)   // d83d
s.charCodeAt(1).toString(16)   // de00
s.codePointAt(0).toString(16)  // 1f600

d83d and de00 are not characters at all. They are halves that only mean something together. Think of a long word hyphenated across two lines: each half is a piece of ink, and only the pair is the word. A tool that counts lines gets 2. A tool that counts words gets 1.

Without u, the engine reads units

A regex without the u flag works on code units. That explains every surprise:

"πŸ˜€".match(/./g)             // ["\ud83d", "\ude00"]
"πŸ˜€".replace(/./g, "*")      // "**"
/^[πŸ˜€]$/.test("πŸ˜€")          // false
/^[πŸ˜€πŸ˜]$/.test("😁")        // false
/πŸ˜€+/.exec("πŸ˜€πŸ˜€")[0]        // "πŸ˜€"

The dot returns two lone surrogates, which print as escapes because they are not valid text on their own. A class like [πŸ˜€] is really a class of two units, so it matches one half and $ complains about the other. The quantifier case is the nastiest: + binds to the last unit only, so πŸ˜€+ means β€œthe high half, then one or more low halves”. On πŸ˜€πŸ˜€ it matched just one emoji and gave up.

With u, the engine reads code points

Add u and both the pattern and the input are decoded into code points before matching. The same five lines now behave:

"πŸ˜€".match(/./gu)            // ["πŸ˜€"]
"πŸ˜€".replace(/./gu, "*")     // "*"
/^[πŸ˜€]$/u.test("πŸ˜€")         // true
/^[πŸ˜€πŸ˜]$/u.test("😁")       // true
/πŸ˜€+/u.exec("πŸ˜€πŸ˜€")[0]       // "πŸ˜€πŸ˜€"

lastIndex still counts code units. Stepping /./gu through "aπŸ˜€b" gave matches at indexes 0, 1 and 3, with lastIndex 1, 3 and 4. The emoji advanced the position by two.

The flag also unlocks \u{...}, which writes a code point by its number. /^\u{1F600}$/u.test("πŸ˜€") is true. Without u the same text means something else entirely: \u{3} on its own matched "uuu", because the engine reads u and then the counted quantifier {3}. A range such as [\u{1F600}-\u{1F64F}] without u was a SyntaxError, β€œRange out of order in character class”. With u it matched.

u makes the grammar stricter too. /\-/ is fine without it, but new RegExp("\\-", "u") throws β€œInvalid escape”. Pointless escapes become errors instead of silent no-ops, which catches typos.

Negated classes change as well. /^\W$/.test("πŸ˜€") was false because the emoji is two units, and /^\W$/u.test("πŸ˜€") was true.

How other flavours compare

Python’s str already holds code points, so no flag is needed. I ran len('πŸ˜€') and got 1, and re.fullmatch('.', 'πŸ˜€') matched. Python 3 re patterns are Unicode-aware by default for str. PCRE and Perl have their own switches (UTF mode, use utf8) and I did not exercise them here. Do not assume the JavaScript behaviour is universal: it is a consequence of JavaScript’s string representation, not of regex in general.

About the video

The video is β€œMathias Bynens: RegExp.prototype.unicode | JSConf EU 2015”, on the JSConf channel, published 19 October 2015, 25 minutes 17 seconds long. I couldn’t read a transcript, so this is what the description and chapters support. The talk covers the ES2015 u flag, code point escapes, and the effect on the dot, character classes, class escapes and the i flag. I clipped it to the part between the quick Unicode intro and the browser-support chapter. It is a decade old, and the later chapters on transpiling u patterns to ES5 and on matching Unicode categories talk about what was then a proposal. Property escapes now exist, and the next lesson covers them. English per its title and description.

What I did not run

Browsers other than V8, PCRE and Perl’s UTF modes, and the ES5 transpilation tool the talk describes. The claims about Python are from Python 3.9 only.

Next

u fixes code units versus code points. The bigger win is matching by what a code point is, not by listing it: Unicode property escapes. For the string-level background, see strings and Unicode.

Check yourself

  1. 01Why does /^.$/.test('πŸ˜€') return false while /^.$/u.test('πŸ˜€') returns true?

    Without u the dot matches one UTF-16 code unit, and the emoji is two (a surrogate pair), so ^.$ sees two units and fails. With u the dot matches one code point, which is the whole emoji.

  2. 02What does 'πŸ˜€'.replace(/./g, '*') produce, and why?

    It produces '**', two asterisks, because each half of the surrogate pair is matched and replaced separately. Adding u gives a single '*'.

  3. 03You write /^\u{3}$/ without the u flag. What does it match?

    The string 'uuu'. Without u, \u is just a letter u, and {3} is a counted quantifier on it. The code point escape \u{...} is only recognised with the u flag.

  4. 04Does a code point always equal one thing a user would call a character?

    No. A flag emoji is two code points, and an e with an accent can be written as two code points. u fixes code units versus code points, not code points versus characters. Lesson 35 covers that gap.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↡ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark