diff --git a/src/shared/escape-html.ts b/src/shared/escape-html.ts new file mode 100644 index 0000000..f1965fe --- /dev/null +++ b/src/shared/escape-html.ts @@ -0,0 +1,18 @@ +/** + * HTML-escape a string for safe interpolation into HTML content and attributes. + * Escapes the 5 characters that have special meaning in HTML: & < > " ' + * + * Single-pass implementation: one regex scan with a lookup map instead of + * five chained .replace() calls. + */ +const ESC_MAP: Record = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'", +}; + +export function escapeHtml(text: string): string { + return text.replace(/[&<>"']/g, (ch) => ESC_MAP[ch]); +}