Case folding, normalization and graphemes

Intermediate · 5 min

Why ignore-case misses ß and İ, why é can be two code points that a regex treats as different text, and what Intl.Segmenter counts as a character.

Before thisUnicode code points and the u flagUnicode property escapesFlags: ignore case, global and multiline

Dylan Beattie · 15 min · from 7:29

Case folding, normalization and graphemes

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

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

What you'll learn

  • Ignore-case in a regex uses simple one-to-one case folding. /straße/i does not match STRASSE, because ß folds to two letters and no one-to-one rule can express that.
  • Flavours disagree at the edges. With u, JavaScript's /s/i matches ſ and /k/i matches the Kelvin sign. Python's re.I does too. Python's re.I also lets i match İ and ı, and JavaScript's does not.
  • The same visible é can be one code point or two (e plus a combining accent), and /^é$/ matches only the form it was written in. Normalize both sides to NFC or NFD first.
  • A user-perceived character is a grapheme cluster. A family emoji is 5 code points and 8 UTF-16 units. Intl.Segmenter counts it as 1, and regex can't, apart from \X in PCRE/Perl and \p{RGI_Emoji} in v mode.
  • Strip accents by normalizing to NFD and removing \p{M}. To match letters that carry combining marks, use [\p{L}\p{M}].

Three ways the same text stops matching

You search a document for straße, ignoring case, and the user typed STRASSE. No match. You search for café and one copy of the word in the file is invisible to you: it prints identically and still doesn’t match. You count characters to enforce a limit and a single emoji uses up 8. All three are the same mistake: assuming that “same text” and “same code points” mean one thing. This lesson takes them in turn.

Case folding is one-to-one

The i flag asks the engine to treat letters that differ only by case as equal. For ASCII that is easy. For other scripts it is mostly fine too: /é/i.test("É") and /ω/i.test("Ω") were both true on Node 26.

The trouble is that real casing is not always one-to-one. The uppercase of ß is the two letters SS: "straße".toUpperCase() gave STRASSE. A regex flag folds a single code point to a single code point, so it cannot say “one character equals two”. I ran it:

/straße/i.test("STRASSE")    // false
/straße/iu.test("STRASSE")   // false

Python is the same: re.search('straße', 'STRASSE', re.I) returned nothing. Python offers a different tool, str.casefold(), which turns ß into ss; comparing 'STRASSE'.casefold() with 'straße'.casefold() was True. That is string comparison, not regex, but for “equal ignoring case” it is often the correct answer.

Flavours also disagree about odd pairs. In JavaScript without u, /s/i.test("ſ") (the long s) was false; with iu it was true. The same happened for /k/i against the Kelvin sign U+212A. Python’s re.I matched both, and also matched i against the Turkish İ and ı, which JavaScript refused in both modes. The Turkish case is why "I".toLocaleLowerCase("tr") returned ı: some languages disagree about what the lowercase of I even is. A regex has no locale, so it cannot follow them. If your data is Turkish, normalize case with the locale-aware string methods before matching.

Normalization: é two ways

Unicode allows an accented letter to be written two ways. é can be the single code point U+00E9 (precomposed), or e followed by U+0301, a combining acute accent (decomposed). They look the same and compare differently:

const a = "é", b = "é";
a === b               // false
a.length, b.length    // 1, 2
/^é$/.test(b)         // false
/^.$/u.test(b)        // false
/^\p{L}+$/u.test(b)   // false

Even \p{L}+ failed, because the accent is a mark (category M), not a letter. Text can arrive in either form depending on where it came from; I did not measure which sources produce which.

The fix is to pick one form and convert both sides. NFC composes where it can, NFD decomposes fully. b.normalize("NFC") === a was true. If you need to accept marks as part of a letter, /^[\p{L}\p{M}]+$/u.test(b) was true.

Decomposition also gives you a cheap accent stripper:

"Crème Brûlée".normalize("NFD").replace(/\p{M}/gu, "")   // "Creme Brulee"
"Crème Brûlée".replace(/\p{M}/gu, "")                    // "Crème Brûlée"

The second line removed nothing, because the original string was precomposed and has no separate mark to remove. Python has the same split: unicodedata.normalize('NFC', 'é') == 'é' was True.

There are also the compatibility forms NFKC and NFKD, which fold look-alikes. "fi".normalize("NFKC") gave fi, and "²" became 2. That is lossy, so use it for search keys, not for stored text.

A character is a grapheme cluster

What a person calls one character is a grapheme cluster. Here is what I counted:

é (e + U+0301)   length 2   code points 2   graphemes 1
👨‍👩‍👧              length 8   code points 5   graphemes 1
🇺🇸               length 4   code points 2   graphemes 1
👍🏽               length 4   code points 2   graphemes 1
नमस्ते            length 6   code points 6   graphemes 3

The grapheme column comes from Intl.Segmenter with granularity: "grapheme". Reversing "aéb" by code point put the accent on the wrong letter (b́ea). Reversing by grapheme gave béa. Truncating "👍🏽ab" to 3 code points cut it to 👍🏽a, while 3 graphemes kept 👍🏽ab.

Regex mostly cannot do this. JavaScript has no \X: new RegExp("\\X", "u") threw “Invalid escape”. PCRE and Perl have \X for one grapheme cluster, and printf 'e\xcc\x81x\n' | pcre2grep -u -o '\X' printed two matches. In JavaScript’s v mode, /^\p{RGI_Emoji}$/v matched the family emoji whole, but that covers emoji only. For counting, truncating and reversing user text, segment first and regex second.

About the video

“The Mötley Crüe Guide to Unicode Normalization” by Dylan Beattie, published 19 August 2024, is 14 minutes 35 seconds. Its description is about code pages giving way to Unicode, and what happens when software treats å as an a with a ring. Its chapters include “Handling characters in Unicode”, “Unicode normalization” and “Normalization forms and complexity”. I clipped to those three, from about 7:29 to 12:58. I couldn’t read a transcript, so I can’t say whether it shows NFC versus NFD concretely or mentions graphemes. It isn’t about regex or JavaScript. This lesson’s case folding and grapheme sections are not in this clip; the “Cases, Code Points and Collations” video in the deeper links covers case, and its description mentions JavaScript and the German spelling council. English per its title and description.

What I did not run

RE2 and Java case folding, the locale-aware matching some flavours offer, Intl.Collator, and any Unicode version differences in grapheme rules. Locale-specific folding for Turkish is shown only through toLocaleLowerCase, not through a regex.

Next

Unicode is where the text gets complicated. The engine is where the time goes. How a backtracking engine matches shows what happens inside, one step at a time.

Check yourself

  1. 01Why does /^é$/.test('e\u0301') return false when both strings print as é?

    The pattern is the single code point U+00E9. The string is two: e and the combining acute U+0301. A regex compares code points, not appearance. Normalize both with .normalize('NFC') first.

  2. 02How would you remove accents from 'Crème Brûlée' in JavaScript?

    'Crème Brûlée'.normalize('NFD').replace(/\p{M}/gu, '') gives 'Creme Brulee'. NFD splits each accented letter into base plus mark, and the replace deletes the marks. Without normalizing first, nothing is removed if the text was precomposed.

  3. 03Does the i flag make /straße/i match 'STRASSE'?

    No, in either JavaScript or Python. The i flag applies one-to-one folding, and the uppercase of ß is the two letters SS. In Python, compare with str.casefold() instead.

  4. 04'👍🏽' has length 4. How many characters would a person say it has, and what counts that?

    One. It is a thumbs-up plus a skin-tone modifier, 2 code points and 4 UTF-16 units. new Intl.Segmenter('en', {granularity: 'grapheme'}) segments it as 1.

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