string#
Immutable UTF-16 code-unit sequences. .length counts code
units, not Unicode code points; characters outside the BMP take
two units. [...s] and Array.from(s) iterate code points.
length on an ASCII string returns the character count.
"hello".length; // 5
Length on a surrogate-pair character counts the units, not the character.
"🌍".length; // 2 (surrogate pair)
Iterate code points with the spread.
[..."🌍"].length; // 1
Common methods.
"hello".toUpperCase(); // "HELLO"
"hello".includes("ell"); // true
"hello".slice(1, 4); // "ell"
Template literals interpolate with ${expr} and preserve
newlines.
const s = "hello";
`${s}, world`; // "hello, world"
Tagged templates pass the parts and interpolated values into a function. Used by SQL builders, GraphQL, i18n.
function html(strings, ...values) {
return strings.raw.reduce((acc, s, i) =>
acc + s + (values[i] != null ? escape(values[i]) : ""), "");
}
References#
Casting for
String(x)andJSON.stringify.Data Structures for iteration helpers on strings.