Command Palette

Search for a command to run...

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

Three ways to count

The last sample is the flag of India: two "regional indicator" letters, I and N, that the screen draws as one flag.

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?

Three ways to count

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

cat 3 3 3
😀 2 1 1
👍🏽 4 2 1
👨‍👩‍👧 8 5 1
🇮🇳 4 2 1