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:

Entity Mapping Reference

Character Character Name Encoded Entity
& Ampersand &
< Less-than &lt;
> Greater-than &gt;
" Double quote &quot;
' Apostrophe / Single quote &#39;

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: &lt;script&gt;alert(&quot;Hello &amp; &#39;Welcome&#39;!&quot;);&lt;/script&gt;

Important Behavior Details