By the end of this tutorial, you’ll escape HTML special characters safely using Lodash’s _.escape() before rendering user content.
01
Core Syntax
Call _.escape(string) on untrusted text.
02
HTML Entities
Convert & < > " ' to entities.
03
XSS Mitigation
Render user input as text, not live HTML.
04
vs unescape
Reverse encoding with _.unescape() when needed.
05
Templates
Know when _.template auto-escapes.
06
Production Tips
Escape on output; prefer framework escaping when available.
Fundamentals
What Is _.escape()?
_.escape() converts HTML-special characters in a string into their entity equivalents so browsers display them as text instead of parsing them as markup. It is a building block for XSS mitigation when you must inject strings into HTML contexts manually.
💡
Beginner tip
Think of _.escape(userComment) as “make this safe to drop inside a paragraph tag as plain text.”
Comment threads, admin dashboards, email previews, and server-rendered snippets all benefit from escaping anything that did not come from your own trusted templates.
Foundation
📝 Syntax
Pass the string that may contain HTML-significant characters:
javascript
_.escape(string)
Syntax Rules
string — the text to escape.
Escaped chars — &, <, >, ", '.
Return value — a new string safe for HTML text insertion.
Not a sanitizer alone — combine with CSP, framework escaping, and server validation.
_.escape() is a small, dependable step toward safer HTML output when you must compose markup manually. Encode untrusted strings, render them as text, and keep dangerous tags from executing in the browser.
Continue with _.escapeRegExp() when you build dynamic regular expressions, or _.unescape() to reverse entity encoding.
Use these points when rendering untrusted strings in HTML.
5
Core concepts
🔒01
Entities
Encode & < > " '.
Basics
🛡02
XSS layer
Text, not live HTML.
Security
💬03
Comments
Escape user content.
Pattern
🔄04
unescape
Decode when needed.
Related
📝05
escapeRegExp
Next: regex safety.
Next step
❓ Frequently Asked Questions
_.escape() replaces HTML-significant characters with their entity equivalents so the string displays as text instead of markup.
No. It is one helpful layer. Also use CSP, framework escaping, input validation, and safe DOM APIs like textContent.
Ampersand, less-than, greater-than, double quote, and single quote are converted to HTML entities.
_.escape() targets HTML entities. _.escapeRegExp() escapes regular expression metacharacters for safe RegExp construction.
Yes. Use _.unescape() to decode HTML entities back to characters when appropriate.
Usually store raw text and escape on output. Escaping at storage time can complicate editing and double-encoding.
Did you know?
Setting element.textContent treats input as plain text automatically—_.escape() is most valuable when you concatenate strings into HTML manually. Reverse encoding with _.unescape(); for RegExp literals use _.escapeRegExp() instead.