QuestenaPractice that shows what to review next
Topic lesson

Strings and templates: choose the right unit and boundary

About 6 min

Questions stay in the language in which they were published.

These questions ask you to read string literals, interpolation, indexing, slicing, searches, replacement, splitting, and iteration. Before calculating, decide whether the operation works in code units, code points, indexes, or substrings.

Track the representation and the method contract

Strings cannot be changed in place, so string methods produce results without rewriting the source. Single and double quotes create the same kind of value; choose a delimiter that avoids or correctly escapes matching quote characters. Backticks mark a template literal and permit direct line breaks. A placeholder evaluates its expression and converts the result to text: if count is 3, a placeholder expression count * 4 inserts 12. The same placeholder-like characters in an ordinary quoted string stay literal.

SignalProcedure and small example
length or bracket indexingCount UTF-16 code units. text[2] reads one code unit at position 2, and an unavailable bracket position produces undefined.
slice(start, end)Include start and stop before end. "garden".slice(2, 5) produces "rde" and leaves the original string unchanged.
includes, startsWith, or endsWithKeep case exactly as written and return a boolean. startsWith checks only the beginning, endsWith only the ending, and includes searches anywhere.
replace with a string search valueChange the first match only and return a new string. "ha ha".replace("ha", "ho") produces "ho ha".
split(separator)Return an array of the surrounding substrings. "a|b".split("|") produces ["a", "b"], with the separator omitted.
for...of iterationProcess Unicode code points. A supplementary code point stored as a surrogate pair is combined for iteration even though length counts its two code units.

The tempting wrong routes

Try it

Question 28

Classify the statements about expression interpolation in JavaScript strings. Select all that apply.

  1. A template placeholder evaluates its expression
  2. An ordinary quoted string interpolates the same way
  3. The expression result is converted to text
  4. Interpolation inserts source code without evaluation
Question 31

Given text = "planet", what does text.slice(1, 4) return, and what happens to text?

  1. lane, with text unchanged
  2. lan, with text unchanged
  3. lan, with text shortened
  4. pla, with text unchanged
Question 36

A for...of loop processes a string containing one supplementary Unicode code point encoded as a surrogate pair. How many loop values represent that code point?

  1. Two, one for each code unit
  2. One, for the combined code point
  3. Zero, because it is not basic Unicode
  4. A runtime-dependent number
Start drillPractice this topic
Strings and templates: choose the right unit and boundary · Questena