Skip to article content
FrontendXLesson 10 / 30

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.

beginner · about 35 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

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.

snippet.js
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.

  1. Exercise 1Predict

    What does this line print?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    console.log('\u{1F600}'.length, [...'\u{1F600}'].length, 'hello'.slice(-3));
    Choose the best answer
  2. Exercise 2Explain

    Explain why 'cafe' + a combining accent has a different length and equality result than the precomposed 'café'.

    starter.text
    console.log('cafe\u0301' === 'caf\u00e9');

    Reveal the reference answer
    reference.text
    The 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.

  3. 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.javascript
    function reverseText(text) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    function 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.

  4. 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.javascript
    function lastChar(text) {
      return text[text.length - 1];
    }
    console.log(JSON.stringify(lastChar('a\u{1F600}')));

    Reveal the reference answer
    reference.javascript
    function 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.

  5. Exercise 5Test

    Write assertions that prove slice accepts negative indices while substring clamps them to zero.

    starter.javascript
    function assertEqual(actual, expected, label) {
      if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual);
    }

    Reveal the reference answer
    reference.javascript
    assertEqual('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.

  6. Exercise 6Interview

    How would you safely truncate user-facing text that may contain emoji?

    Reveal the reference answer
    reference.text
    I 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

Related resources

#

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.

© 2026 FrontendX. All rights reserved.