Skip to content

Instantly share code, notes, and snippets.

@MatheusMFranco
Last active August 16, 2024 09:38
Pure HTML Escape Sanitizer
//Preview: https://codepen.io/matheusfranco/pen/abgEqMm
export const sanitizeHTML = (input = '', remainHtml = false): string => {
let cleaned = input.replace(/<(iframe|script|object|embed|style|link)[\s\S]*?>[\s\S]*?<\/\1>/gi, '');
return remainHtml ? cleaned : cleaned.replace(/<\/?[^>]+>/gi, '');
};
const unsafeHTML = '<p>Hello World!</p><script>alert(\'hi\')</script><b>footer</b>';
console.log(sanitizeHTML(unsafeHTML)); // Output: Hello World!footer
console.log(sanitizeHTML(unsafeHTML, true)); // Output: <p>Hello World!</p><b>footer</b>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment