Escape HTML with a tagged template
Write a tagged template that escapes HTML text, joins arrays and accepts markup from trusted strings.
You build a snippet of HTML with a template literal and drop a user's name into it. If the name is <b>Ada</b>, a browser parsing the output as HTML renders Ada in bold.
const name = '<b>Ada</b>'
console.log(`<p>${name}</p>`) // <p><b>Ada</b></p>The template literal pastes the value in as it is and does no escaping.
A tag that escapes the values
A tagged template calls a function instead of building the string itself. The function gets the fixed pieces as an array and the interpolated values as the remaining arguments. It can escape the values and leave your own markup alone.
For <p>${'a'} and ${'b'}</p> I logged the pieces: three strings, <p>, and and </p>, and two values, a and b. The strings array is always one entry longer than the values.
const esc = (v) => String(v).replace(/[&<>"']/g, (c) =>
({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c])
class Safe { constructor(s) { this.s = s } toString() { return this.s } }
const raw = (s) => new Safe(String(s))
const part = (v) => Array.isArray(v) ? v.map(part).join('') : v instanceof Safe ? v.s : esc(v)
const html = (strings, ...values) =>
raw(strings.reduce((out, s, i) => out + part(values[i - 1]) + s))esc swaps the five characters that matter in text and in quoted attributes in one pass, so esc('<') gives < and esc('<') gives &lt;.
part decides what happens to each value. An array is joined after each item goes through part, a Safe value passes untouched, and anything else is escaped. html returns a Safe too, so a nested html call is not escaped a second time.
Render input as text
const name = '<b>Ada</b>'
const tags = ['a&b', '"quoted"', "it's"]
const badge = raw('<b>new</b>')
console.log(String(html`<p title="${name}">${name} ${badge}</p>`))
// <p title="<b>Ada</b>"><b>Ada</b> <b>new</b></p>
console.log(String(html`<ul>${tags.map((t) => html`<li>${t}</li>`)}</ul>`))
// <ul><li>a&b</li><li>"quoted"</li><li>it's</li></ul>The name comes out as text in the attribute and in the body. The <b> I marked with raw stays a tag, and each array item sits in its own <li> with no commas between them. A number such as 0 prints as 0.
Keep escaped values in text nodes or ordinary quoted attributes such as title. URL attributes need a separate scheme check, and scripts, styles and event handler attributes use different parsing rules. Insert raw or nested markup only in text positions, and reserve raw for markup you control. For plain text in an existing DOM node, assign textContent.