JAVASCRIPT / CHAPTER 15
Text, Unicode, and explicit normalization
IntermediateChoose the unit of text that an algorithm actually processes.
By the end of this chapter
- Distinguish UTF-16 units from code points
- Normalize text without changing the original
- Specify empty and whitespace-only input
The idea
A string is immutable: trimming or replacing text produces another string. Decide which changes a task permits before building a pipeline. Trimming ends, collapsing internal spaces, and changing case are different policies. Retain the original when an application needs a faithful display value alongside a normalized search key.
JavaScript string length and numeric indexes count UTF-16 code units. String iteration combines surrogate pairs into code points, so spreading a string can produce fewer elements than its length. Neither measure always counts user-perceived characters, because combining marks and joined emoji can contain several code points. State the unit explicitly; use the simple ASCII subset when an exercise requires byte-like character reasoning.
const original = " A😀 ";
const text = original.trim();
console.log(text.length, [...text].length);
console.log(original.startsWith(" "));3 2 true
The emoji occupies two UTF-16 units but one code point. Trimming returns a separate string.
Try it yourself
Normalize surrounding whitespace and reject empty results while preserving the original display text.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
Open JavaScript coding challengesCHECK YOUR UNDERSTANDING