Skip to content

escapeHtml

Edit

Escapes characters with special meaning in HTML text and attributes.

escapeHtml.ts
const entities: Record<string, string> = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;",
};
/** Escapes the five characters with special meaning in HTML text and attributes. */
export const escapeHtml = (value: string): string => {
return value.replace(
/[&<>"']/g,
(character) => entities[character] ?? character
);
};
Terminal
wget -O src/lib/escapeHtml.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/escapeHtml.ts
escapeHtml.example.ts
import { escapeHtml } from "./escapeHtml";
const safe = escapeHtml(`<p title="Tom & Jerry">`);
  • value (string) — Untrusted text.
  • Escapes &, <, >, double quotes, and single quotes.
  • This does not sanitize complete HTML documents.