0 day streak
javascript / intermediate
Snippet

Tagged Template Literals for Sanitization

Tagged templates allow you to parse template literals with a function. This is powerful for creating DSLs or, as shown here, automatically escaping user input to prevent XSS attacks.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
function safeHTML(strings, ...values) {
return strings.reduce((acc, str, i) => {
const val = String(values[i] || '').replace(/</g, '&lt;').replace(/>/g, '&gt;');
return acc + str + val;
}, '');
}
const userInput = '<img src=x onerror=alert(1)>';
const message = safeHTML`User said: ${userInput}`;
console.log(message); // User said: &lt;img src=x onerror=alert(1)&gt;
Breakdown
1
function safeHTML(strings, ...values) {
The function receives static strings as an array and dynamic values separately.
2
replace(/</g, '&lt;')
Replaces dangerous HTML characters with safe entities.
3
strings.reduce(...)
Interleaves the static parts of the string with the processed dynamic values.
4
safeHTML`User said: ${userInput}`;
Invokes the 'tag' function without parentheses on the template string.