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 |
< |
< |
Less-than (tag open) |
> |
> |
Greater-than (tag close) |
" |
" |
Double quote (attribute delimiter) |
' |
' |
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,
<div class="box">
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:
- No Extended Named Entities: Entities such as
,©, or—are not present in Lodash's internal map. They will pass through completely unmodified. - Limited Numeric Character Support: Lodash
specifically accommodates
'(including variations with leading zeros such as'), but it does not parse generic decimal (<) or hexadecimal (<) numeric character references. - Security Risks with Direct DOM Insertion:
Reconstituting DOM elements using
_.unescapecreates unescaped strings that contain raw markup. Passing this output directly to DOM sinks such asElement.innerHTMLwithout 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.