Sub topic 3
Converting Values to Strings
This chapter assumes you know arrays, map, and basic regular expression syntax. It covers conversion, regex methods, Unicode, locale sorting, tagged templates, wrapper objects, and building strings.
Converting Values to Strings
String(value) converts any value safely, including null and undefined. Calling value.toString() throws on those two. Template literals give the same result as String() for most values.
console.log(String(null), String(42), `${[1, 2]}`); // null 42 1,2Regular Expression Methods
matchAll needs the g flag. It yields every match with its capture groups and index. match with g returns only the matched strings. search returns the position of the first match, or -1.
const log = "id=1 id=22 id=333";
for (const m of log.matchAll(/id=(\d+)/g)) {
console.log(m[1], m.index); // 1 0, then 22 5, then 333 11
}
console.log(log.match(/\d+/g)); // ["1", "22", "333"]
console.log(log.search(/=/)); // 2Unicode, Code Points, and Normalization
length counts UTF-16 code units. An emoji outside the Basic Multilingual Plane takes two of them, called a surrogate pair. Spreading a string iterates by code point instead. normalize makes visually identical strings compare equal.
const s = "a\u{1F600}";
console.log(s.length, [...s].length); // 3 2
console.log(s.codePointAt(1)); // 128512
console.log("e\u0301".normalize("NFC") === "\u00e9"); // trueLocale-Aware Sorting
By default, sort() orders strings by code unit, so "C" sorts before "a". Use localeCompare or an Intl.Collator to get the order a reader expects.
console.log(["b", "a", "C"].sort((x, y) => x.localeCompare(y, "en"))); // ["a", "b", "C"]
const collator = new Intl.Collator("en", { numeric: true });
console.log(["item10", "item2"].sort(collator.compare)); // ["item2", "item10"]Tagged Templates and String.raw
A tag function receives the literal parts and the interpolated values as separate arguments. String.raw keeps backslashes exactly as written.
const shout = (strs, ...vals) =>
strs.reduce((out, s, i) => out + s + (i < vals.length ? String(vals[i]).toUpperCase() : ""), "");
console.log(shout`hi ${"ada"}!`); // hi ADA!
console.log(String.raw`C:\new\folder`); // C:\new\folderPrimitives Versus String Objects
new String("x") creates an object, not a primitive. Its typeof is "object", and it fails === against the primitive "x". Don't use new String.
console.log(typeof new String("x"), "x" === new String("x")); // object falseBuilding Strings Efficiently
Modern engines make += in a loop fast. Collecting the parts in an array and calling join is often clearer when you need separators.
Exercise
Why does "a\u{1F600}".length return 3, and how do you count its visible characters?
Show answer
length counts UTF-16 code units, and the emoji uses a surrogate pair of two units. [..."a\u{1F600}"].length counts code points and returns 2.
Exercise
Sort ["file10", "File2", "file1"] case-insensitively with numeric awareness.
Show answer
arr.sort(new Intl.Collator("en", { numeric: true, sensitivity: "base" }).compare) gives ["file1", "File2", "file10"].