How Lodash unescape Decodes HTML Entities

This article provides an overview of how the Lodash utility function _.unescape translates escaped HTML entities back into their raw DOM characters. It details the specific native dictionary map used by Lodash, explains the regular expressions driving the parser, and explores the boundaries of using this method to restore markup structures for the Document Object Model (DOM).

The Native Translation Dictionary in Lodash

Lodash does not maintain an exhaustive dictionary of all HTML5 named entities. Instead, _.unescape relies on a targeted, native lookup dictionary designed specifically to reverse the characters converted by _.escape.

Inside the Lodash source code, this dictionary is structured via an internal mapping object typically referenced as htmlUnescapes:

Entity Code Unescaped Character Target Function
& & Ampersand
&lt; < Less-than (tag open)
&gt; > Greater-than (tag close)
&quot; " Double quote (attribute delimiter)
&#39; ' Single quote / apostrophe

How the Parsing Mechanism Works

When _.unescape(string) is executed, the string is evaluated using a compiled regular expression (reEscapedHtml) that searches strictly for these five patterns:

const reEscapedHtml = /&(?:amp|lt|gt|quot|#(0+)?39);/g;

When a match occurs, Lodash feeds the captured entity directly into the dictionary lookup function:

const unescapeHtmlChar = (entity) => htmlUnescapes[entity];

Because this map explicitly targets structural characters (<, >, &, ", '), running _.unescape across escaped markup will immediately convert entities back into raw DOM node syntax. For instance, &lt;div class=&quot;box&quot;&gt; seamlessly converts to <div class="box">.

Parsing DOM Structures and Limitations

While _.unescape successfully reconstitutes basic DOM tags and attribute delimiters, its native dictionary has strict limitations:

  1. No Extended Named Entities: Entities such as &nbsp;, &copy;, or &mdash; are not present in Lodash's internal map. They will pass through completely unmodified.
  2. Limited Numeric Character Support: Lodash specifically accommodates &#39; (including variations with leading zeros such as &#0039;), but it does not parse generic decimal (&#60;) or hexadecimal (&#x3C;) numeric character references.
  3. Security Risks with Direct DOM Insertion: Reconstituting DOM elements using _.unescape creates unescaped strings that contain raw markup. Passing this output directly to DOM sinks such as Element.innerHTML without secondary sanitization exposes applications to Cross-Site Scripting (XSS).

For standard markup translation requiring only the five core HTML-safe characters, Lodash’s htmlUnescapes dictionary provides an efficient, lightweight string replacement without the performance overhead of instantiating full browser DOM parsing utilities like DOMParser.