Strings and Unicode
Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.
What you will be able to do
#- Explain why string length counts UTF-16 code units rather than characters.
- Choose between slice, substring and array indexing deliberately.
- Process text containing emoji and combining marks without splitting characters.
Overview
#Strings are immutable
A string never changes in place. Methods such as toUpperCase and replace return a new string. Indexing with square brackets returns a single UTF-16 code unit as a one-character string.
UTF-16 code units
JavaScript strings are sequences of 16-bit code units. Characters outside the Basic Multilingual Plane, such as most emoji, need two code units called a surrogate pair. That is why length counts code units and why naive indexing can split a character in half.
console.log('a'.length); // 1
console.log('\u{1F600}'.length); // 2, one emoji is two code units
console.log([...'\u{1F600}'].length); // 1, the spread respects code points
Choosing an extraction method
slice takes a start and an optional end and accepts negative indices counted from the end. substring clamps negatives to zero and swaps reversed arguments. The legacy substr takes a length instead of an end and should be avoided in new code. For code-point aware work prefer Array.from or the spread operator over index arithmetic.
Searching and comparing
includes, startsWith and endsWith read more clearly than indexOf comparisons. localeCompare sorts according to locale rules, which matters for accented letters. normalize converts between composed and decomposed forms so that visually identical text compares equal.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does this line print?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptconsole.log('\u{1F600}'.length, [...'\u{1F600}'].length, 'hello'.slice(-3));Exercise 2Explain
Explain why 'cafe' + a combining accent has a different length and equality result than the precomposed 'café'.
starter.textconsole.log('cafe\u0301' === 'caf\u00e9');Reveal the reference answer
reference.textThe first string is the letter e followed by a combining acute accent code point, so it has five code units. The second uses the precomposed character e-acute, so it has four. They render the same but are different sequences, so strict equality is false. Calling normalize('NFC') on both makes them equal.Authored expected output: false
Unicode allows the same visible text to be encoded in more than one way. Normalization is required before comparing or hashing user text.
Exercise 3Implement
Implement `reverseText(text)` so it reverses by code point and keeps emoji intact. Running `console.log(reverseText('ab\u{1F600}'))` should print the emoji followed by 'ba'.
starter.javascriptfunction reverseText(text) { // your code here }Reveal the reference answer
reference.javascriptfunction reverseText(text) { return [...text].reverse().join(''); }Authored expected output: \u{1F600}ba
The spread splits the string into code points, reverse flips the order and join rebuilds the string. Splitting with split('') would have broken the surrogate pair.
Exercise 4Debug
This function is meant to return the last character but returns an empty string for a two-code-unit emoji. Find and fix the bug.
starter.javascriptfunction lastChar(text) { return text[text.length - 1]; } console.log(JSON.stringify(lastChar('a\u{1F600}')));Reveal the reference answer
reference.javascriptfunction lastChar(text) { const chars = [...text]; return chars[chars.length - 1]; } console.log(JSON.stringify(lastChar('a\u{1F600}')));Authored expected output: \u{1F600}
Indexing by length - 1 returns the low surrogate code unit of the emoji, which is not a valid character on its own. Spreading into code points first keeps the pair together.
Exercise 5Test
Write assertions that prove slice accepts negative indices while substring clamps them to zero.
starter.javascriptfunction assertEqual(actual, expected, label) { if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual); }Reveal the reference answer
reference.javascriptassertEqual('hello'.slice(-2), 'lo', 'slice counts from the end'); assertEqual('hello'.substring(-2), 'hello', 'substring clamps to zero'); assertEqual('hello'.slice(1, 3), 'el', 'slice end is exclusive'); console.log('all assertions passed');Authored expected output: all assertions passed
slice treats a negative start as an offset from the end, while substring treats any negative argument as zero. Both use an exclusive end index.
Exercise 6Interview
How would you safely truncate user-facing text that may contain emoji?
Reveal the reference answer
reference.textI convert the string to an array of code points or use Intl.Segmenter to get grapheme clusters, then cut on a cluster boundary and append an ellipsis. I never slice by raw index, because that can split a surrogate pair or a combining sequence and produce a broken glyph. I also check the visible length after normalization so the limit matches what the user sees.The answer should mention code points or grapheme clusters, boundary-safe cutting and normalization, rather than raw index slicing.
Common misconceptions
#- string.length returns the number of visible characters.
- slice and substring behave identically for negative arguments.
- Two strings that look identical always compare as strictly equal.
Follow-up practice
#- javascript-foundations-regular-expressions
- javascript-foundations-template-literals
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.