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.

JavascriptSecurity Boundaries

Code

javascriptsnippet
17 lines
// 标签模板:插值先经过转义再拼进模板,原始串用 tag.raw 另取
const ESCAPES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' };

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: &lt;b&gt; seizing &quot;&amp;&quot; &lt;/b&gt;</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

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `escapeHtml` at load time.