HTML Escape And Sanitize Input
Escape HTML special characters and strip dangerous tags from user input to prevent XSS in server-rendered templates.
Code
export function escapeHtml(str){return String(str).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,''');}export function sanitizeHtml(html,{allowedTags=['b','i','em','strong','a','p','br']}={}){return escapeHtml(html).replace(/<\/?([a-z0-9]+)\b[^&]*>/gi,(full,tag)=>allowedTags.includes(tag.toLowerCase())?full.replace(/</g,'<').replace(/>/g,'>'):'');}Report a problem with this exampleOpens a pre-filled issue on GitHub.