HTML Escape Characters: 5 Entities and Escape Functions
November 11, 2026 · 9 min read
HTML Escape Characters: The 5 Entity Codes and How to Escape HTML
HTML escape characters are the five reserved characters you swap for entity codes so a browser shows them as text. The swaps are < to <, > to >, & to &, " to " and ' to '. Below you'll get the full table, working escape functions for JavaScript, Python and PHP, and the rules that keep escaping from turning into an XSS bug.
Which Characters Need HTML Escaping?
Searches for "escape characters html" usually come down to these five. Every other character, from é to ©, can go into a UTF-8 page as itself. The five below are special because the HTML parser reads them as markup.
| Character | Named entity | Decimal | Hex | Where it breaks things |
|---|---|---|---|---|
< less-than | < | < | < | Text: it starts a tag |
> greater-than | > | > | > | Rarely; escaped by convention |
& ampersand | & | & | & | Text and attributes: it starts an entity |
" double quote | " | " | " | Inside a double-quoted attribute |
' single quote | ' (HTML5 only) | ' | ' | Inside a single-quoted attribute |
The code points come straight from the WHATWG list of named character references, where lt; maps to U+003C and amp; to U+0026. A standard escape function converts all five, because the same code usually writes both text and attribute values.
What about ? It's a character reference too, but it adds a non-breaking space rather than protecting a reserved character, so it isn't an escape in this sense. For codes that insert a character, such as ©, see our list of HTML symbol codes.
What Does ' Mean in HTML?
' is a numeric character reference for the apostrophe, Unicode U+0027. People also call it an HTML escape sequence or escape code. The &# opens it, 39 is the decimal code point, and the semicolon closes it. Add an x for hex: ' is the same character.
You'll see it everywhere because of history. HTML 4.01 never defined ', which came from XML, so older browsers and escapers avoided it. HTML5 does define ', but escaping libraries kept the numeric forms. That's why Python and Django output ' and PHP outputs '.
Named references are easier to read. Numeric ones work for any code point, even when no name exists. Both forms need the trailing semicolon. Browsers forgive a missing one on some legacy names such as & and <, but that's error recovery, not something to rely on.
How Do You Escape HTML Tags So They Show as Text?
Replace the angle brackets with entities. To print a tag on a page, write this in your source:
<p>Wrap the content in a <div class="card"> element.</p>
The browser displays Wrap the content in a <div class="card"> element. with the tag visible as plain text.
Wrapping a snippet in pre and code keeps its spacing but escapes nothing, so you still need < inside. In Markdown you can skip the manual work, because code spans and fenced blocks escape their contents for you. The Markdown code block guide covers that syntax.
Escaping Text vs Attribute Values
The HTML spec sets different rules for each place a character can appear. According to the WHATWG syntax section, normal text must not contain a literal < or an ambiguous ampersand. A double-quoted attribute value must not contain a literal ", and a single-quoted one must not contain '.
<p>Tom & Jerry <3</p>
<input value="She said "hi"">
<input value='It's fine'>
Each line renders as intended: the text reads Tom & Jerry <3, and each input holds its quote. The spec bars unquoted attribute values from containing spaces, quotes, =, <, > or backticks, so always quote them.
Entity escaping only works where the HTML parser decodes entities. Inside script and style elements, < stays as four literal characters. URLs need percent-encoding, so use encodeURIComponent for query values. The OWASP XSS Prevention Cheat Sheet lists the right encoder for each context.
How to Escape HTML in JavaScript
JavaScript has no built-in escape-HTML function, but the DOM gives you something better. Setting textContent stores a string as text and never parses it as HTML. It's the safest way to HTML escape text in the browser.
const p = document.createElement("p");
p.textContent = userComment; // shown literally, tags and all
list.append(p);
If userComment holds <img src=x onerror=alert(1)>, the reader sees that text and nothing runs. Assigning the same string to innerHTML would execute the handler. We prefer textContent over any escape function, because there's no string handling to get wrong.
Frameworks apply the same idea. React escapes every string you render in JSX, and dangerouslySetInnerHTML is the deliberate opt-out. Vue escapes {{ }} interpolation, while the v-html directive inserts raw HTML. Treat both opt-outs as places that need sanitised input.
When you must build an HTML string, for example in a Node script that writes a file, escape it yourself:
function escapeHtml(str) {
return String(str)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
escapeHtml(`<a href="x">Tom & Jerry's</a>`);
// <a href="x">Tom & Jerry's</a>
Order matters. Swap the ampersand first, because each later replacement adds new ampersands. Put the ampersand step last and <b> comes out as &lt;b&gt;.
To unescape in the browser, let DOMParser decode the entities:
function unescapeHtml(str) {
const doc = new DOMParser().parseFromString(str, "text/html");
return doc.documentElement.textContent;
}
unescapeHtml("Tom & Jerry <3"); // Tom & Jerry <3
Scripts don't run in a parsed document, but any real tags in the input are dropped from the result. Only feed it text you know is escaped.
HTML Escape in Python and PHP
Python ships html.escape and html.unescape in the standard library. With the default quote=True, escape converts all five characters, writing the apostrophe as '. The Python html module docs list the details.
import html
html.escape("<a href=\"x\">Tom & Jerry's</a>")
# '<a href="x">Tom & Jerry's</a>'
html.escape("5 > 3 & 'ok'", quote=False)
# "5 > 3 & 'ok'"
html.unescape("<p> ' ' '")
# "<p> ' ' '"
Older tutorials still show cgi.escape. Python 3.8 removed that function, and Python 3.13 removed the whole cgi module, so use html.escape. Template engines handle most of this for you. Django escapes all five characters in every template variable by default, unless you mark it safe. Jinja2 only does so when you enable autoescape, which select_autoescape() turns on for .html templates. For a full script built on html.escape, see our text to HTML converter guide.
PHP's equivalent is htmlspecialchars. Since PHP 8.1 its default flags are ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, so both quote types are escaped.
echo htmlspecialchars("<a href='x'>Tom & Jerry</a>");
// <a href='x'>Tom & Jerry</a>
On older PHP versions the default left single quotes alone, so pass ENT_QUOTES explicitly if your code runs anywhere older. htmlspecialchars_decode reverses it. Most other languages ship an escaper too, such as html.EscapeString in Go and CGI.escapeHTML in Ruby.
Why Escaping Prevents XSS, and Where It Stops
Cross-site scripting happens when user text lands in a page and the browser runs it as code. If a comment field accepts <script> and you print it raw, every visitor who loads the page runs that script. Escape it, and the parser sees only harmless text.
Escaping has two limits. First, it's all or nothing: escaped HTML shows up as visible tags. If you want users to post some HTML, such as rendered Markdown, you need a sanitiser that keeps an allow list of safe tags. The Python Markdown guide shows that step with nh3.
Second, escape once, at output. Escaping on input and again in the template produces double escaping:
html.escape(html.escape("<b>"))
# '&lt;b&gt;'
The page then displays <b> instead of <b>. If you see stray & text on a live site, this is usually the cause. Store raw text, and let the template escape it on the way out.
HTML Escapes Inside Markdown Files
Markdown accepts the same entities. The CommonMark 0.31.2 spec treats named and numeric references as the characters they stand for, except inside code spans and code blocks. There, < stays literal, and a bare < is escaped for you.
Raw HTML passes straight through most Markdown renderers, so Markdown from untrusted users needs sanitising after rendering. Backslash escapes like \* are a separate mechanism for Markdown's own symbols, covered in how to escape Markdown characters.
Try it below. The first block uses entities, the second uses real tags, and the third shows double escaping.
The preview shows the div tag as text, the bold and italic as formatting, and the double-escaped line as a visible <b>. Our editor's preview renders raw HTML like <b> and <kbd>, with scripts and event handlers stripped.
Quick Answers About Escaping HTML Characters
The HTML escape rules fit in one table: five characters, five entities, ampersand first. Use textContent in the browser, html.escape in Python and htmlspecialchars in PHP, and escape once at output. To test entities against real tags in your own document, open the editor and check the live preview on the right. When you need a full page, the Markdown to HTML converter turns your file into an HTML document.