HTML Escape And Sanitize Input

Escape HTML special characters and strip dangerous tags from user input to prevent XSS in server-rendered templates.

JavascriptSecurity Boundaries

Code

javascriptsnippet
1 line
export function escapeHtml(str){return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');}export function sanitizeHtml(html,{allowedTags=['b','i','em','strong','a','p','br']}={}){return escapeHtml(html).replace(/&lt;\/?([a-z0-9]+)\b[^&]*&gt;/gi,(full,tag)=>allowedTags.includes(tag.toLowerCase())?full.replace(/&lt;/g,'<').replace(/&gt;/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

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.