javascript / expert
Snippet
Contextual Escaping via Tagged Templates
Tagged template literals allow you to parse template literals with a function. This is an expert pattern for implementing Domain Specific Languages (DSLs) or, as shown here, automatic security escaping to prevent XSS attacks.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
function safeHTML(strings, ...values) {return strings.reduce((acc, str, i) => {const value = String(values[i] || '');const escaped = value.replace(/[&<>"']/g, m => ({'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}[m]));return acc + str + escaped;}, '');}const userSupplied = '<img src=x onerror=alert(1)>';const html = safeHTML`<div>${userSupplied}</div>`;
Breakdown
1
safeHTML`...`
Invokes the safeHTML function with strings and interpolated values separately.
2
strings.reduce(...)
Iterates through the static string parts and weaves in the escaped dynamic values.
3
values[i]
Accesses the raw data inserted into the template before it becomes part of the final string.