Strings are immutable sequences of UTF-16 code units. Template literals give interpolation, multi-line text and tagged templates.
Three ways to write a string
const single = 'single';
const double = "double";
const name = "Asha";
const tpl = `Hi ${name}, 2 + 3 = ${2 + 3}, upper: ${name.toUpperCase()}`;
console.log(single, double);
console.log(tpl);
const multi = `line 1
line 2`;
console.log(multi);single double
Hi Asha, 2 + 3 = 5, upper: ASHA
line 1
line 2Indexing and immutability
const s = "JavaScript";
console.log(s.length, s[0], s.at(-1), s.charAt(4), s[99]);
console.log(s.slice(0, 4), s.slice(-6), s.substring(4, 0));
console.log(s.charCodeAt(0), String.fromCharCode(74));10 J t S undefined
Java Script Java
74 JUnicode gotcha
const emoji = "😀";
console.log(emoji.length, [...emoji].length);
console.log("héllo".length, "héllo".normalize("NFD").length);
const flag = "👍🏽";
console.log(flag.length, [...flag].length);2 1
5 6
4 2Escapes and raw strings
console.log("tab:\tend", "quote: \"", 'it\'s');
console.log("\u0041\u{1F600}");
console.log(String.raw`C:\new\table`);tab: end quote: " it's
A😀
C:\new\tableTagged templates
A tag is a function called with the literal's string pieces and the interpolated values — used by String.raw, styled-components, GraphQL gql, SQL builders and HTML escapers.
function highlight(strings, ...values) {
return strings.reduce(
(out, str, i) => out + str + (i < values.length ? `[${values[i]}]` : ""),
""
);
}
const item = "coffee", price = 3.5;
console.log(highlight`One ${item} costs $${price}.`);
function show(strings, ...values) {
console.log(strings, values);
}
show`a${1}b${2}`;One [coffee] costs $[3.5].
[ 'a', 'b', '' ] [ 1, 2 ]Why is "😀".length equal to 2?