HTML Entity Encode/Decode

Use this HTML entity encoder decoder to convert special characters to HTML entities and back. Encode text for safe embedding or decode entity references.

HTML entity encoding converts characters that have special meaning in HTML into safe entity references so they display correctly instead of being interpreted as markup. This tool encodes the five critical characters (&, <, >, ", ') and decodes named, decimal, and hexadecimal entity references back to readable text. Paste text, click Encode or Decode, and copy the result - all processing runs locally in your browser.

Ad
Ad

About HTML Entity Encode/Decode

The Five Characters That Must Be Encoded

These five characters have special meaning in HTML. If user-supplied text contains any of them and is inserted into a page without encoding, the browser will interpret them as HTML syntax rather than display them as text.

CharacterNamed EntityNumeric EntityWhy It Must Be Encoded
&&amp;&#38;Starts an entity reference - without encoding, &copy; would render as the copyright symbol
<&lt;&#60;Opens an HTML tag - <script> would execute code
>&gt;&#62;Closes an HTML tag
"&quot;&#34;Terminates an attribute value in double quotes
'&apos;&#39;Terminates an attribute value in single quotes

Encoding these five characters is the minimum required for safe HTML output. The & character is the most commonly missed - any literal ampersand in HTML text content should be &amp;, even if it is not followed by a valid entity name.

Three Types of Entity References

HTML supports three different syntaxes for entity references. All three produce the same result in the browser, but they have different use cases.

TypeSyntaxExampleResultNotes
Named&name;&copy;Copyright symbolHuman-readable, limited to defined names
Decimal&#number;&#169;Copyright symbolUses Unicode code point in base 10
Hexadecimal&#xHEX;&#xA9;Copyright symbolUses Unicode code point in base 16

Named entities are easier to read in source code but only cover about 2,200 characters. Numeric entities can represent any of the 149,000+ Unicode characters. Hexadecimal is often preferred because Unicode charts and programming languages typically show code points in hex.

Common Named Entities

EntityCharacterDescription
&nbsp;Non-breaking spacePrevents line break between two words
&mdash;Em dashLong dash used in punctuation
&ndash;En dashMedium dash for ranges (1-10)
&laquo; / &raquo;GuillemetsUsed as quotation marks in some languages
&copy;Copyright symbolUsed in footer notices
&reg;Registered trademarkCircle-R symbol
&trade;TrademarkSuperscript TM
&hellip;EllipsisThree dots as single character
&euro;Euro signEuropean currency symbol
&pound;Pound signBritish currency symbol

HTML Encoding and XSS Prevention

Cross-site scripting (XSS) is one of the most common web security vulnerabilities. It happens when user input is inserted into a page without proper encoding, allowing an attacker to inject executable scripts.

ContextDangerous InputWhat Happens Without EncodingSafe Output
Text content<script>alert('xss')</script>Script executes in visitor's browser&lt;script&gt;alert('xss')&lt;/script&gt;
Attribute value" onmouseover="alert('xss')Event handler injected into element&quot; onmouseover=&quot;alert('xss')
URL attributejavascript:alert('xss')Script runs when link is clickedReject entirely - encoding is not enough

HTML entity encoding handles text content and attribute value contexts. For URLs (href, src attributes), you must also validate the URL scheme - encoding a javascript: URL does not make it safe. For JavaScript string contexts, you need JavaScript-specific escaping instead.

Encoding in Different Contexts

ContextEncoding NeededTool
HTML text contentHTML entity encodingThis tool
HTML attribute valuesHTML entity encoding + quote the attributeThis tool
URL query parametersPercent encoding (encodeURIComponent)URL Encoder
JSON valuesJSON string escapingJSON Formatter
Base64 transportBase64 encodingBase64 Encoder

Using the wrong encoding for the context is a security risk. HTML encoding in a URL context or URL encoding in an HTML context both leave the output vulnerable to injection.

Encoding in Programming Languages

LanguageFunctionExample
JavaScript (DOM)textContent (auto-escapes)element.textContent = userInput
JavaScript (manual)No built-in - use a library or replace()str.replace(/&/g, '&amp;').replace(/</g, '&lt;')
Pythonhtml.escape()html.escape('<script>')
PHPhtmlspecialchars()htmlspecialchars($input, ENT_QUOTES, 'UTF-8')
RubyCGI.escapeHTML()CGI.escapeHTML('<b>bold</b>')
Gohtml.EscapeString()html.EscapeString("<script>")

Modern template engines (React, Vue, Angular, Jinja2, Razor) encode output by default. The dangerous patterns are raw HTML insertion: dangerouslySetInnerHTML in React, v-html in Vue, and |safe in Jinja2. These bypass encoding and should only be used with trusted content.

When to Use Named vs Numeric Entities

SituationRecommendedWhy
The 5 critical charactersNamed (&amp; &lt; etc.)Most readable in source code
Common symbols (copyright, trademark)Named (&copy; &trade;)Widely recognized
Rare Unicode charactersNumeric (&#x2603; for snowman)No named entity exists for most Unicode characters
UTF-8 document with non-ASCII charactersUse the character directlyIf the document encoding is UTF-8, entities are unnecessary for display characters

Worked Example: Encoding a User Comment

A user submits the comment <b>Check this & see!</b> on a blog. If the site renders that string raw, the browser treats <b> as a bold tag and & as the start of an entity. The page looks fine in this harmless case, but the same channel lets an attacker submit <script>fetch('/api/keys')</script> and run code in every visitor's session.

Encode step by step: First replace every & with &amp; (order matters - do this first or you double-encode later entities). Next swap < for &lt;, > for &gt;, " for &quot;, and ' for &#39;. The comment becomes &lt;b&gt;Check this &amp; see!&lt;/b&gt;. The browser now shows the literal angle brackets and ampersand instead of applying them as markup. Drop that output into your page template and the attack surface for the comment field disappears.

Why Entity Decoding Is Harder Than It Looks

Decoding is trickier than encoding. A decoder needs to handle named entities with and without trailing semicolons, decimal entities like &#169;, hexadecimal entities like &#xA9; or &#XA9;, surrogate pairs for characters above U+FFFF, and legacy entities the HTML parser still recognises for backward compatibility. This tool uses the browser's own HTML parser (via a hidden textarea element) to match the behaviour of real rendering engines, so edge cases like &notin; versus &not;in resolve correctly.

Common mistakes when rolling your own decoder: assuming every entity ends in a semicolon (the parser accepts &copy in some contexts), treating &#x2028; and &#x2029; as safe (they break JavaScript string literals), or iterating replacements in a way that lets &amp;lt; become < after two passes. Round-tripping through the browser's parser avoids all of these.

How Many Named Entities Exist?

The HTML Living Standard defines 2,231 named character references, according to the WHATWG named-characters table. That covers common symbols (&copy; &reg; &trade;), Greek letters (&alpha; &beta;), mathematical operators (&sum; &int; &infin;), and arrows. Unicode itself defines over 149,000 code points as of Unicode 16.0 (September 2024), so named entities cover only about 1.5% of Unicode. For anything outside that set - emoji, CJK ideographs, rare mathematical symbols - use numeric references or the raw UTF-8 character if your document declares that encoding.

Named entities are case-sensitive: &Copy; (capital C) produces the double-struck capital C, while &copy; produces the copyright symbol. Typo-prone pairs like &lt; versus &Lt; (less-than with dot) and &sup; versus &supe; (superset versus subset-equal) trip up hand-written markup regularly. Numeric entities sidestep this entirely.

When You Do Not Need to Encode

Modern frameworks encode output by default, so you do not need to pre-encode text before passing it into JSX, Vue templates, or Jinja2. The framework's template engine handles it at render time. You only need this tool when you are building HTML by string concatenation (legacy templates, email generators, static file exports), pasting text into an HTML source file manually, or sanitising content that will be inserted via innerHTML. For the reverse direction - decoding - common scenarios include reading scraped HTML, processing RSS feeds, or debugging API responses that return HTML-encoded strings.

For URL components, use the URL Encoder and Decoder instead - percent encoding and HTML entity encoding are not interchangeable. For converting between HTML and Markdown or prettifying tangled HTML, reach for the HTML Prettifier after decoding.

Common Mistakes to Avoid

  • Encoding twice. Running encoded text through an encoder again turns &amp; into &amp;amp;. Always know whether a string has already been encoded before processing it.
  • Using HTML encoding in a JavaScript string. </script> inside a JavaScript block ends the script tag regardless of HTML encoding. Use JavaScript string escapes (\u003c/script\u003e) or serve the data via a JSON endpoint.
  • Trusting &apos; in old browsers. Internet Explorer 8 and older did not recognise &apos;. Use &#39; for single quotes if you need to support ancient browsers - modern browsers handle both.
  • Encoding inside attribute values but leaving the attribute unquoted. <a href=/page class=foo> is valid HTML but lets an attacker inject attributes by including a space in the value. Always quote attribute values.
  • Assuming server-side encoding is enough. Reactive UI frameworks re-render based on client state. If state contains raw HTML, a server encode does not help - the client must handle it too.

All processing happens in your browser. Your text is never sent to any server, making this tool safe for encoding sensitive content or debugging security issues.

Sources

Frequently Asked Questions

What are HTML entities?

HTML entities are special sequences that represent characters which have reserved meaning in HTML, such as angle brackets, ampersands, and quotation marks. For example, the less-than sign is represented as &lt; and the ampersand as &amp;. Using entities prevents browsers from misinterpreting these characters as HTML markup.

When should I encode HTML entities?

You should encode HTML entities whenever you display user-generated content on a web page, insert text into HTML attributes, or embed code examples in documentation. This prevents cross-site scripting (XSS) vulnerabilities and ensures special characters render correctly in the browser.

What is the difference between named and numeric HTML entities?

Named entities use human-readable references like &amp;amp; for the ampersand, while numeric entities use the Unicode code point like &amp;#38; or &amp;#x26;. Both produce the same result. Named entities are easier to read in source code, while numeric entities can represent any Unicode character.

Does this tool handle all Unicode characters?

Yes. The tool encodes the five critical HTML characters (ampersand, less-than, greater-than, double quote, single quote) which are necessary for safe HTML embedding. The decoder handles named entities, decimal numeric entities, and hexadecimal numeric entities for the full Unicode range.

Link to this tool

Copy this HTML to link to this tool from your website or blog.

<a href="https://toolboxkit.io/tools/html-entity-encoder-decoder/" title="HTML Entity Encode/Decode - Free Online Tool">Try HTML Entity Encode/Decode on ToolboxKit.io</a>