Escape HTML special characters

Replace & < > " and ' with HTML entities.

JavaScript Version 1.0.0 · MIT · .md

escape-html-special-characters.js
function escapeHtml(text) { return text.replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]); }

Input & expected output

Input

"<b>Ana & Rui</b>"

Expected output

"&lt;b&gt;Ana &amp; Rui&lt;/b&gt;"

The edge case

Input

"O'Brien"

Expected output

"O&#39;Brien"

Know the limits

  • Escape untrusted text before placing it in HTML, including HTML email templates. This protects text content and quoted attribute values, not URLs, scripts or CSS.

The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.

Source & maintenance

Based on Escape HTML special characters from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

Uses the single-pass replacement map. Original MDX retained as inert source evidence.

Maintained by Oveyon. Original source commit: 14b481cf60df. This edition’s file: contents/escape-html-special-characters.mdx in akamind/1loc, commit 0a77f131b22d. Read the license.

Local fixture scope · Node.js 22.23.2 · reviewed October 28, 2026. No external service is required.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.