How Lodash unescape Converts HTML Entities
Lodash’s _.unescape method converts specific HTML
entities within a string back to their corresponding literal characters.
It reverses the operation of _.escape by scanning the input
string for encoded sequences and replacing them with standard
characters. This article explains the internal mechanics of
_.unescape, the specific entities it targets, and how
Lodash optimizes this replacement process.
The Targeted HTML Entities
Unlike full HTML parsers or browser-based decoders,
_.unescape is designed for lightweight, predictable string
sanitation. It specifically maps five predefined HTML entities back to
their original characters:
&becomes&<becomes<>becomes>"becomes"'becomes'
Lodash explicitly restricts its scope to these five characters
because they represent the core entities needed to prevent HTML
injection and preserve basic markup syntax. It intentionally ignores
other named entities (such as © or
) and arbitrary numeric character references
(such as /).
The Underlying Mechanism
At the source code level, Lodash accomplishes the decoding process through three primary components: a lookup map, regular expressions, and string coercion.
Mapping Dictionary: Lodash initializes an internal dictionary object containing the key-value pairs of the target entities and their decoded characters:
const htmlUnescapes = { '&': '&', '<': '<', '>': '>', '"': '"', ''': "'" };Regex Matching: It uses two regular expressions:
- A test pattern (
reHasEscapedHtml) to check whether the string contains any of the target entities. - A global replacement pattern (
reEscapedHtml) defined roughly as/&(?:amp|lt|gt|quot|#39);/g.
- A test pattern (
String Replacement: When
_.unescape(string)is called, the function first converts the input to a string via Lodash's internaltoStringhelper. If the input is null, undefined, or empty, it returns an empty string.Optimized Execution: Before executing a replacement, the method tests the string with
reHasEscapedHtml.test(string). If no entities match, the string is returned immediately without modification, avoiding unnecessary memory allocation. If entities are found, Lodash invokes standard JavaScript string replacement:return string.replace(reEscapedHtml, (entity) => htmlUnescapes[entity]);Each matched entity serves as a key in the
htmlUnescapesobject, swapping the encoded text for the literal character in a single pass.