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,'>'):'');}What the code does
Count the functions escapeHtml and sanitizeHtml as the entire surface area of HTML Escape And Sanitize Input.
Applying it
Entry signature: export function escapeHtml(str)
Treat escapeHtml as the API: import it, and ignore the supporting code.
Interactive Tools for This Topic
CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.HTML Entity Encoder / DecoderEncode the five HTML-significant characters and decode named or numeric entities, with optional numeric encoding for non-ASCII text.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. The file defines `escapeHtml`, `sanitizeHtml` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.