/** * Escapes HTML special characters to prevent XSS attacks when inserting * untrusted content into HTML. * * Converts the following characters to their HTML entity equivalents: * - `&` → `&` * - `<` → `<` * - `>` → `>` * - `"` → `"` * - `'` → `'` * * @param str - The string containing potentially unsafe HTML characters * @returns The escaped string safe for insertion into HTML content or attributes * * @example * ```typescript * escapeHtml(''); * // Returns: '<script>alert("XSS")</script>' * * escapeHtml('Tom & Jerry'); * // Returns: 'Tom & Jerry' * * escapeHtml('
'); * // Returns: '<div class="foo">' * ``` */ export function escapeHtml(str: string): string { return str .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); }