Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.2 — Unicode, Emoji and String Length
JavaScript · Example 3 of 3 ES2015+

normalize, case and language

Both words print as "café" but are stored differently. \uFB01 is the single ligature character "fi", which NFKC turns into the two letters "fi".

Every character has a Unicode number (a code point), but JavaScript stores strings as 16-bit pieces called UTF-16 code units, so length counts pieces, not characters: one emoji can have a length of 2, 4 or more. Use for...of, spread or Intl.Segmenter to work with real characters, and normalize() before comparing text.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write reverseText(s) that reverses a string without breaking emoji like 😀 (code points are enough here).

02

Write charsLeft(text, max) that returns how many visible characters are left, counting graphemes, so charsLeft("hi👍🏽", 10) returns 7.

Explain it without notes

01

Why is "😀".length equal to 2?

02

What is the difference between a code unit, a code point and a grapheme cluster?

03

How would you count the characters a user sees in a text box?

04

Why can two strings that look identical fail ===, and how do you fix it?

normalize, case and language ES2015+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

café café false
5 4
true
5
file
STRASSE
I İ