9. Strings, template literals, and regular expressions
Strings are immutable UTF-16 sequences — every "mutating" string method
returns a new string. Template literals (`...`) support interpolation
and multi-line strings natively, and tagged templates let a function
intercept and transform the literal before it's assembled — the mechanism
behind libraries like styled-components and safe SQL-templating helpers:
function safeHtml(strings, ...values) {
const escape = (s) => String(s).replace(/[&<>"']/g, c => ({
"&": "&", "<": "<", ">": ">", '"': """, "'": "'",
}[c]));
return strings.reduce((out, str, i) =>
out + str + (i < values.length ? escape(values[i]) : ""), "");
}
const userInput = "<script>alert(1)</script>";
safeHtml`<p>Hello, ${userInput}</p>`;
// "<p>Hello, <script>alert(1)</script></p>" — escaped automatically
Regular expressions (/pattern/flags) are used via .test(), .match(),
.matchAll(), and String.prototype.replace. Named capture groups make
extraction readable:
const re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const m = "2026-09-13".match(re);
m.groups.year; // "2026"