QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Escape HTML

Verified

Escapes &, <, >, " and ' so untrusted text can be safely inserted into HTML.

  • html
  • security
  • xss
  • sanitize

Install

npx shadcn@latest add https://quicksnip.dev/r/escape-html.json

Code

const ENTITIES: Record<string, string> = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;",
};

/** Escapes the five HTML-significant characters so text can be safely inserted into markup. */
export function escapeHtml(input: string): string {
  return input.replace(/[&<>"']/g, (ch) => ENTITIES[ch]);
}

Usage

escapeHtml('<b>"Tom" & Jerry</b>'); // "&lt;b&gt;&quot;Tom&quot; &amp; Jerry&lt;/b&gt;"