Escape HTML Entities for Output

Escape untrusted text before inserting it into HTML so angle brackets and quotes cannot break out of the surrounding context.

JavascriptSecurity Boundaries

Code

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

export function escapeHtml(text) {
  if (text === null || text === undefined) return "";
  return String(text).replace(/[&<>"']/g, (char) => ENTITIES[char]);
}