Unicode code points and the u flag
Why /^.$/ rejects a single emoji in JavaScript, how UTF-16 code units differ from code points, and what the u flag and \u{...} change.
Character classesThe dot and newlinesDotall, sticky and Unicode flags
Unicode code points and the u flag
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
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
Why 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.
What 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 '*'.
You 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.
Does 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
Notes are saved to your account.
Everything else on this page works without one β progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.