JavaScript

String Template Tag — SQL / HTML Sanitiser

by @admin
10h ago
Apr 28, 2026
Public
A tagged template literal that automatically escapes interpolated values, preventing SQL injection (server-side) or XSS (client-side) from untrusted input. The html tag HTML-encodes values; the sql tag parameterises values and returns a { text, values } tuple ready for a parameterised query driver.
JavaScript
// HTML escape tag — safe client-side interpolation
const escapeMap = { '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' };
const escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => escapeMap[c]);

function html(strings, ...values) {
  return strings.reduce((out, str, i) =>
    out + str + (values[i] !== undefined ? escapeHtml(values[i]) : ''), '');
}

// SQL parameterisation tag — pairs with pg / mysql2
function sql(strings, ...values) {
  let text = '';
  strings.forEach((str, i) => { text += str; if (i < values.length) text += `$${i + 1}`; });
  return { text, values };
}

// Usage
const name = '<script>alert(1)</script>';
document.querySelector('#output').innerHTML = html`<p>Hello, ${name}!</p>`;
// → <p>Hello, &lt;script&gt;alert(1)&lt;/script&gt;</p>

const userId = 42;
const query = sql`SELECT * FROM users WHERE id = ${userId}`;
// → { text: 'SELECT * FROM users WHERE id = $1', values: [42] }
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.