How do I decode HTML entities in JavaScript?

Dark navy cover card with the title 'How do I decode HTML entities in JavaScript?' in white and a green accent bar

To decode HTML entities in JavaScript in the browser, parse the string with DOMParser and read its textContent. That turns &lt;b&gt; Tom &amp; Jerry into <b> Tom & Jerry without running any scripts. In Node.js there is no DOM, so use a library such as he or entities.

The common "set innerHTML on a div" trick also decodes entities, but it can execute attacker HTML. Avoid it for anything you didn't write yourself.

How to decode HTML entities in JavaScript in the browser

The safest built-in way to decode HTML entities in the browser is DOMParser with the text/html type. The parsed document is detached from your page, so nothing in it runs.

function decodeEntities(str) {
  const doc = new DOMParser().parseFromString(str, 'text/html');
  return doc.documentElement.textContent;
}

decodeEntities('Tom &amp; Jerry &copy; &#60;3 &#x3C;3');
// "Tom & Jerry © <3 <3"

MDN's DOMParser reference explains why this is safe: with text/html, script elements are marked non-executable and events are not fired. The catch: scripts and handlers can run if you later insert those parsed nodes into the visible page. Take the text out and nothing else.

textContent also strips any tags in the input. If the string was &lt;b&gt;hi&lt;/b&gt;, you get the literal text <b>hi</b>. If the string held real tags like <b>hi</b>, you get just hi.

Why the innerHTML trick is risky

Setting innerHTML on an element in your page decodes entities, but it parses the input as live HTML. Any markup in that string becomes real elements first.

MDN calls innerHTML "probably the most common vector for cross-site scripting (XSS) attacks." Script tags injected this way don't run, but other HTML does. The innerHTML reference shows this exact case:

const div = document.createElement('div');
div.innerHTML = "<img src='x' onerror='alert(1)'>"; // the alert fires

The element was never added to the page, and the handler still ran. A comment field, an API response or a CMS title can carry that string. If you then read div.textContent to "decode" it, the damage is already done.

Some guides swap the div for a textarea and read .value. That works because of parsing rules most readers of your code won't know. Use DOMParser and make the intent obvious.

How to decode HTML entities in Node.js

Node.js has no document or DOMParser, so decoding entities there needs a library. Two packages cover nearly every case.

The entities package is the decoder that htmlparser2 uses:

import { decodeHTML } from 'entities';

decodeHTML('asdf &amp; &yuml; &uuml; &apos;');
// "asdf & ÿ ü '"

It also has decodeXML for XML input, which only knows the small XML entity set. In strict mode, entities not ending in a semicolon are ignored.

The he package decodes "as if used in a text context" in an HTML document:

import he from 'he';

he.decode('Tom &amp; Jerry &copy;'); // "Tom & Jerry ©"
he.decode('foo&bar', { isAttributeValue: true }); // "foo&bar"
he.decode('foo&ampbar', { strict: true }); // throws a parse error

The isAttributeValue option matters because HTML applies different rules to character references inside attribute values. The strict option throws on sloppy input instead of guessing, which is what you want in tests.

Both libraries also run in the browser. If you already ship one, skip the DOMParser helper.

Which method fits where

Pick the method by where the code runs and whether the input is trusted. This table covers the usual cases.

Situation Method Runs scripts in input?
Browser, any input DOMParser + textContent No
Browser, untrusted input div.innerHTML Yes, avoid
Node.js or server code he.decode or decodeHTML from entities No DOM involved
Quick one-off check An HTML entity decoder in the browser No

For a one-off string, paste it into OnlineViewer's HTML decoder instead of writing code. The tool runs in the page and makes no network requests, so the text stays on your machine.

The three kinds of entities you're decoding

HTML entities, properly called character references, come in three forms: named, decimal and hexadecimal. Any decoder you pick must handle all three.

The MDN glossary entry defines them. Named references sit between & and ;, such as &lt; for < and &copy; for ©. Decimal ones start with &# and digits, so &#60; is <. Hexadecimal ones use &#x or &#X: &#x3C; is also <.

Hand-written regex decoders fail here. A replace with five entries handles &amp;, &lt;, &gt;, &quot; and &apos;, then breaks on &eacute;, &#x2014; or &nbsp;. The named character reference list in the HTML standard is long, and some names are valid both with and without the trailing semicolon, such as &amp and &copy. Nobody gets that legacy rule right by hand.

Common problems after decoding

Most decoding bugs come from double encoding or from decoding at the wrong step. Both show up as stray entity text on screen.

Text still shows &amp;lt;. The string was encoded twice. One decode gives &lt;, not <. Decoding in a loop until nothing changes hides the bug and can turn real text like a literal &lt; in a code sample into a tag. Find the layer that encodes twice, often a template engine escaping a value the API already escaped.

Decoded text is then put back with innerHTML. After decoding, <script> in the text is a real angle bracket again. Write it with textContent, which MDN recommends for plain text; it shows the characters and creates no elements. The post on which characters to escape in HTML covers the reverse direction.

URL-encoded text instead of HTML entities. %2F and %3A are percent-encoding, not entities, and need decodeURIComponent. The difference is explained in HTML encoding vs URL encoding.

JSON with escaped characters. & inside a JSON string is a JSON escape that JSON.parse handles. See how to unescape a JSON string.

My take and a limitation

My take: decode as late as possible and only once, right before the text reaches a textContent or a non-HTML output like a CSV file. Decoding early, then passing the string through more code, is how decoded < and > end up back in innerHTML.

The limitation of the DOMParser helper is that it needs a browser. It won't work in Node.js or any other runtime without a DOM, and textContent drops tags you might have wanted to keep. If you want decoded HTML that keeps its markup, a decoder alone won't do. You need a sanitizer too.

FAQ

How do I decode & in JavaScript?

In the browser, parse the string with new DOMParser().parseFromString(str, 'text/html') and read documentElement.textContent. In Node.js, call decode from the he package or decodeHTML from the entities package.

Is the innerHTML trick for decoding entities safe?

Not with a div or span. Setting innerHTML on an element in the page can run event handlers such as onerror on an injected img tag. DOMParser builds an inert document where scripts don't run.

Can I decode HTML entities in Node.js without a library?

Node.js has no DOM, so DOMParser and innerHTML aren't available. A regex handles a few named entities, but the HTML list is long, so the he or entities package is the reliable choice.

Why does my text still show &lt; after decoding?

The string was encoded twice. One decode turns &lt; into <. Fix the code that encodes it twice rather than decoding in a loop.

Do I need to decode entities before putting text in textContent?

Only if the string really contains entities. textContent shows text exactly as given, so an undecoded & appears on screen as &.

Sources