javascript / intermediate
Snippet
Advanced Processing with Tagged Templates
Tagged templates allow you to parse template literals with a function. The first argument contains an array of string literals, and the subsequent arguments are the values of the substituted expressions. This is powerful for creating DSLs, sanitizing HTML, or internationalization.
snippet.js
1
2
3
4
5
6
7
8
9
10
function sanitize(strings, ...values) {return strings.reduce((acc, str, i) => {let val = String(values[i] || '');return acc + str + val.replace(/&/g, '&').replace(/</g, '<');}, '');}const input = '<script>alert(1)</script>';const message = sanitize`User input: ${input}`;console.log(message); // User input: <script>alert(1)</script>
Breakdown
1
function sanitize(strings, ...values)
A tag function that receives string parts and interpolated values separately.
2
strings.reduce((acc, str, i) => ...)
Iterates through the strings and values to reconstruct the final output.
3
val.replace(/</g, '<')
Applies sanitization logic to the interpolated values before joining them.