HTML entity encoder and decoder

Escape special characters for HTML, or turn entities like & back into text.

This tool runs in your browser. We never send what you type or paste to a server.

Which characters need escaping?

In HTML text, escape & as &amp; and < as &lt;. Inside attribute values, also escape quotes: " as &quot; and ' as &#39;. Escaping user input this way is a key defence against cross-site scripting (XSS).

Tick Encode all non-ASCII to also turn characters like é and emoji into numeric entities, for systems that can't handle UTF-8.

Example

<a href="?a=1&b=2">Fish & chips</a>

encodes to

&lt;a href=&quot;?a=1&amp;b=2&quot;&gt;Fish &amp; chips&lt;/a&gt;

which a browser shows as the literal text instead of a link. Quotes are encoded too, so the result is also safe inside an attribute value.

HTML-encoding in JavaScript

JavaScript has no built-in HTML escape function, but it is five replacements. Replace & first, otherwise the ampersands you have just added get escaped a second time:

function escapeHtml(s) {
  return String(s)
    .replaceAll('&', '&amp;')   // first, or the & in &lt; would be escaped again
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;');
}
console.log(escapeHtml('<img src=x onerror="alert(1)">'));   // → &lt;img src=x onerror=&quot;alert(1)&quot;&gt;
console.log(escapeHtml("Tom & Jerry's"));                     // → Tom &amp; Jerry&#39;s
const wrongOrder = (s) => s.replaceAll('<', '&lt;').replaceAll('&', '&amp;');
console.log(wrongOrder('a < b'));                             // → a &amp;lt; b
console.log(escapeHtml(escapeHtml('Fish & chips')));          // → Fish &amp;amp; chips   escaped twice

In the browser you often do not need to escape at all. The DOM has two kinds of property: ones that take text and ones that parse markup. Assign untrusted strings to the text kind and the browser can never treat them as HTML:

// Safe: the value is always treated as text (browser code, not run here)
el.textContent = userInput;
el.setAttribute('title', userInput);
el.append(document.createTextNode(userInput));

// Parses the string as HTML, so <img onerror=...> in userInput runs
el.innerHTML = userInput;
el.insertAdjacentHTML('beforeend', userInput);
el.innerHTML = '<p>' + escapeHtml(userInput) + '</p>';   // safe once escaped

textContent is also faster than innerHTML, because nothing is parsed. Reach for innerHTML only when the string is markup you wrote or have sanitised with a library such as DOMPurify. See MDN on innerHTML.

Decoding entities safely

A common snippet decodes entities by setting innerHTML on a detached div and reading textContent back. Do not use it on untrusted text: the element is still created in your page, so an <img src=x onerror=…> in the input loads and its handler runs even though the div is never shown. DOMParser builds a separate document with scripting off, which is what this tool uses:

new DOMParser().parseFromString('Fish &amp; chips', 'text/html').body.textContent
// "Fish & chips"

Entities come in three spellings that all mean the same character: named (&eacute;), decimal (&#233;) and hex (&#xE9;). For historical reasons, browsers also accept a few old named entities without the closing semicolon, such as &copy and &amp, which is why a stray & in a URL query can turn into a symbol. Writing &amp; in your HTML avoids that.

Context matters: where escaping is not enough

Entity escaping makes a string safe as HTML text and inside a quoted attribute value. It does not make it safe everywhere:

  • Unquoted attributes. <div class=VALUE> can be broken with a space, which is not escaped. Always quote attributes.
  • URLs. href and src accept javascript: URLs, and escaping does not change that. Check that the scheme is http or https.
  • Inside <script> and <style>. Their content is not HTML, so entities are not decoded there. Put data in a data- attribute or a JSON block instead.
  • Escaping twice. If text was escaped before it went into the database and your template escapes it again, readers see &amp; instead of &. Store raw text and escape when you output it.

With Encode all non-ASCII ticked, this tool writes every character above code 126 as a decimal entity, one per code point, so an emoji becomes a single entity rather than two halves:

const toEntities = (s) => [...s].map((c) => (c.codePointAt(0) > 126 ? `&#${c.codePointAt(0)};` : c)).join('');
console.log(toEntities('café 😀'));                            // → caf&#233; &#128512;
console.log('😀'.length, [...'😀'].length);                    // → 2 1   one code point, two UTF-16 units

Python, PowerShell and the shell

Python's html.escape escapes quotes by default (' as &#x27;), and html.unescape follows the same HTML5 rules as browsers:

import html
print(html.escape('<a href="x">Tom & Jerry\'s</a>'))   # → &lt;a href=&quot;x&quot;&gt;Tom &amp; Jerry&#x27;s&lt;/a&gt;
print(html.escape('5 > 3 & "ok"', quote=False))        # → 5 &gt; 3 &amp; "ok"
print(html.unescape('caf&eacute; caf&#233; caf&#xE9;')) # → café café café
print(html.unescape('&copy 2026'))                     # → © 2026   old entities work without the ;

In PowerShell and .NET, use WebUtility; in a shell script, sed does the job if & comes first:

[Net.WebUtility]::HtmlEncode('<a href="x">Tom & Jerry''s</a>')   # → &lt;a href=&quot;x&quot;&gt;Tom &amp; Jerry&#39;s&lt;/a&gt;
[Net.WebUtility]::HtmlDecode('&lt;b&gt;Fish &amp; chips&lt;/b&gt;')  # → <b>Fish & chips</b>
escape_html() { sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g' -e 's/"/\&quot;/g' -e "s/'/\&#39;/g"; }
printf '%s\n' '<b>Fish & "chips"</b>' | escape_html   # → &lt;b&gt;Fish &amp; &quot;chips&quot;&lt;/b&gt;

Questions

What is &amp;nbsp;?

A non-breaking space: a space that stops two words being split across lines.

Should I escape > too?

It's not strictly required in text, but escaping it as &gt; is harmless and common.

When do I need this?

Whenever you show text that came from a user or a database inside HTML: in a template, a blog post that explains HTML, or an email. Most template engines do it for you; this is for the cases where you are building the HTML yourself.

How do I HTML-encode a string in JavaScript?

Replace & with &amp; first, then < with &lt;, > with &gt;, " with &quot; and ' with &#39;. In the browser, the simpler and safer option is to avoid building HTML strings: set element.textContent or use setAttribute, which never interpret the value as markup.

What is the difference between innerHTML and textContent?

innerHTML parses the string as HTML, so tags and event handlers in it take effect. textContent sets plain text, so the same string shows up literally, angle brackets and all. Use textContent for anything that came from a user or an API.

Is HTML escaping enough to prevent XSS?

It is the main defence for text placed in HTML and in quoted attributes, but not for values put into URLs, inline scripts, styles or unquoted attributes. Each of those needs its own handling, and a Content Security Policy adds a second layer.

Why do I see &amp; on my page instead of &?

The text was escaped twice: once before it was stored or passed on, and again when it was displayed. Escape only once, at the point where the text is written into HTML.