HTML Entities Encoded by Lodash escape Method
The _.escape method in the Lodash JavaScript library
converts specific reserved HTML characters in a string into their
corresponding HTML entities. This utility is primarily used to mitigate
Cross-Site Scripting (XSS) attacks by safely encoding user-generated
content before rendering it inside HTML contexts. This guide details the
exact characters Lodash converts, their entity replacements, and how the
method behaves.
Characters Encoded by
_.escape
Lodash's _.escape targets five specific characters that
are critical for HTML parsing and attribute delimiting. It converts
these characters into the following HTML entities:
- Ampersand (
&) becomes& - Less-than sign (
<) becomes< - Greater-than sign (
>) becomes> - Double quote (
") becomes" - Single quote (
') becomes'
Entity Mapping Reference
| Character | Character Name | Encoded Entity |
|---|---|---|
& |
Ampersand | & |
< |
Less-than | < |
> |
Greater-than | > |
" |
Double quote | " |
' |
Apostrophe / Single quote | ' |
Code Example
When passing a string containing these characters into
_.escape, each occurrence is replaced:
const _ = require('lodash');
const unsafeString = '<script>alert("Hello & \'Welcome\'!");</script>';
const safeString = _.escape(unsafeString);
console.log(safeString);
// Output: <script>alert("Hello & 'Welcome'!");</script>Important Behavior Details
- No Double Escaping Prevention: Unlike some
specialized templating engines, Lodash does not check if an entity is
already escaped. For instance,
_.escape('&')results in&amp;. - Other Characters Are Ignored: Characters outside of
this specific list—such as forward slashes (
/), backticks (`), or non-ASCII characters—are not encoded by_.escape. - Reversing the Operation: Lodash provides a
reciprocal method,
_.unescape, which converts&,<,>,", and'back into their raw character representations.