Tagged Templates Escape Interpolations
Tagged template functions intercept interpolations before they are joined: one tag escapes HTML entities, and String.raw exposes the unprocessed raw strings.
Code
// 标签模板:插值先经过转义再拼进模板,原始串用 tag.raw 另取
const ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"' };
function escapeHtml(strings, ...values) {
return strings.reduce((out, chunk, i) => {
const safe = i < values.length ? String(values[i]).replace(/[&<>"]/g, (ch) => ESCAPES[ch]) : '';
return out + chunk + safe;
}, '');
}
const comment = '<b> seizing "&" </b>';
const rendered = escapeHtml`<p>user said: ${comment}</p>`;
console.log(rendered);
console.log('still has raw <b:', rendered.includes('<b'));
// 标签拿到的 strings 带 raw 属性;String.raw 是内置的“不处理”标签
console.log(String.raw`<p>user said: ${comment}</p>`);Output
Captured from a sandboxed run of this snippet in the build pipeline.
<p>user said: <b> seizing "&" </b></p>
still has raw <b: false
<p>user said: <b> seizing "&" </b></p>How it works
Tagged Templates Escape Interpolations reduces to the function escapeHtml.
Applying it
The main signature reads function escapeHtml(strings, ...values)
Running the file prints labeled results such as still has raw <b: — each operation’s effect is visible in the output.
Statements that matter
return strings.reduce((out, chunk, i) => {
const safe = i < values.length ? String(values[i]).replace(/[&<>"]/g, (ch) => ESCAPES[ch]) : '';
return out + chunk + safe;
}, '');
Interactive Tools for This Topic
Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `escapeHtml` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.