Lodash Escape DOM Injection Entity Mapping

This article provides an overview of the strict HTML entity mapping protocols implemented in Lodash’s _.escape utility. It details the specific character dictionary utilized by the library, the regex-driven conversion mechanics, the precise Document Object Model (DOM) injection vectors neutralized by this implementation, and the contextual boundaries where developers cannot rely on it as a comprehensive security sanitizer.

The Explicit Lodash _.escape Character Map

The Lodash _.escape function relies on a hardcoded, minimal conversion protocol specifically designed to neutralize basic HTML delimiter syntax. Internally, Lodash defines an exact five-character dictionary mapping reserved markup characters to their corresponding standard HTML entities:

The internal implementation uses a regular expression—historically defined as /[&<>"']/g—to detect any occurrences of these characters within a string. When matched, each targeted character is indexed directly against an object map (htmlEscapes) to return its replacement entity. Characters outside of this five-character set, including forward slashes (/), backticks (`), and control characters, remain unaltered.

DOM Injection Vectors Neutralized by the Protocol

The conversion protocol employed by _.escape strictly targets two primary DOM injection contexts:

1. Element Node Body Injection

When injecting dynamic strings directly into HTML element bodies (such as <div> or <p> tags), unescaped < and > characters permit an attacker to close the current element or introduce executable markup, such as <script> or <img onerror=...> elements. Converting < to &lt; and > to &gt; causes the browser's HTML parser to treat the injected content as pure text nodes rather than executable markup tokens. Converting & to &amp; prevents ambiguous or malicious character references from being parsed downstream.

2. Quoted Attribute Breakouts

When data is placed inside quoted HTML attributes (such as <input value="USER_DATA"> or <div data-info='USER_DATA'>), an attacker attempts to break out of the attribute boundary using matching quote characters. By converting " to &quot; and ' to &#39;, Lodash prevents premature termination of the attribute string, keeping the payload safely enclosed within the attribute value.

Architectural Boundaries and Security Limitations

While _.escape mitigates traditional markup injection within text nodes and quoted attributes, it does not conform to comprehensive context-aware encoding standards required for full DOM protection:

Lodash’s _.escape strictly operates as a syntactic HTML character serializer, securing only well-formed, quote-bounded HTML text and attribute nodes.