Use a tagged template to build safe HTML
Build HTML with a tagged template that escapes every interpolated value, so a comment containing markup is shown as text. Node.js 24.
A template literal inserts whatever you give it, so <p>${comment}</p> turns a user's comment into live markup. A tagged template can escape each value before it is inserted, and Node.js 24 runs this one as written.
const escapeHtml = (value) =>
String(value).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
function html(strings, ...values) {
return strings.reduce((out, chunk, i) => out + chunk + (i < values.length ? escapeHtml(values[i]) : ''), '');
}
const comment = '<img src=x onerror="steal()">';
console.log(html`<p class="comment">${comment}</p>`);
console.log(`<p class="comment">${comment}</p>`);
console.log(html`<p>${1 + 1} & ${'a & b'}</p>`);<p class="comment"><img src=x onerror="steal()"></p>
<p class="comment"><img src=x onerror="steal()"></p>
<p>2 & a & b</p>A tag is a function called with the literal chunks and the values separately. The html tag in the example leaves the chunks alone, since you wrote them, and escapes each value, so the onerror payload prints as <img src=x onerror="steal()"> and the browser shows it as text. The plain template on the second line writes the markup as it is. The last line shows the split: the & you typed stays, while the & in the value becomes &. The call form is in the specification for tagged templates.
This escapes for text content and quoted attributes only. It does not make a value safe inside a script block, an unquoted attribute, a style rule or a javascript: URL, and for those you need a different escape, or a templating library with context awareness. If your framework already escapes output, such as React, you do not need this.