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

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

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

Inside the snippet

Count the function escapeHtml as the entire surface area of Escape HTML Entities for Output.

Watch out for

  • The guard text === null || text === undefined short-circuits the flow with an early return when its condition holds.

Putting it to use

Entry signature: export function escapeHtml(text)

Treat escapeHtml as the API: import it, and ignore the supporting code.

Core lines

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

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. The file defines `escapeHtml` at load time.