Lodash _.escape() Method

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 6 Examples + 3 Try It
String utilities

What You’ll Learn

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.

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.

📝 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.
  • Reverse — use _.unescape() to decode entities.
javascript
import escape from "lodash/escape";

const raw = '<script>alert("x")</script>';
const safe = escape(raw);
// -> "&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;"

⚡ Quick Reference

TaskCode patternResult
Escape HTML_.escape(userInput)Entity-encoded string
Script tag_.escape('<script>')Displayed as text
Ampersand_.escape('3 < 5')3 < 5
Reverse_.unescape(str)Decode entities
Template escape taglodash escape interpolate syntaxAuto-escape in templates
RegExp literals_.escapeRegExp(str)Different helper
Mutates?
No

Returns new string

Encodes
& < > " '

HTML-significant

Reverse
_.unescape()

Decode entities

Not this
_.escapeRegExp()

Regex metachars

🧰 Parameters

Arguments to _.escape() and what they control:

string Required

The input that may contain characters with HTML significance.

_.escape('<div>')
return value New string

A copy with special characters replaced by HTML entities.

// -> '&lt;div&gt;'
encoded set Fixed

Escapes ampersand, less-than, greater-than, double quote, and single quote.

_.escape('a & b')
security Important

One layer in depth defense—also validate on server and use CSP headers.

// escape before innerHTML

For RegExp patterns, use _.escapeRegExp()—it escapes different characters.

Examples Gallery

Practical _.escape() patterns with copy-ready code, sample output, and interactive Try It Yourself labs.

📚 Getting Started

Escape dangerous markup before displaying user content.

Example 1 — Escape a script injection attempt

Neutralize a script tag so it renders as harmless text.

javascript
import escape from "lodash/escape";

const raw = '<script>alert("Hello!");</script>';
const safe = escape(raw);

console.log(safe);
// -> "&lt;script&gt;alert(&quot;Hello!&quot;);&lt;/script&gt;"
Try It Yourself

How It Works

Angle brackets and quotes become entities browsers show literally.

Example 2 — Escape markup in a snippet

Show HTML source as text in a code preview panel.

javascript
import escape from "lodash/escape";

const html = "<div>Hello, <strong>world</strong>!</div>";
const preview = escape(html);

console.log(preview);
Try It Yourself

How It Works

Users see the literal tags instead of bold rendering.

Example 3 — Sanitize a user comment

Escape untrusted comment text before inserting into the DOM.

javascript
import escape from "lodash/escape";

const userComment = 'Nice post! <img src=x onerror=alert(1)>';
const safeComment = escape(userComment);

console.log(safeComment);
Try It Yourself

How It Works

Event-handler attributes inside tags cannot execute when shown as escaped text.

Example 4 — Escape comparison operators

Display mathematical expressions containing less-than signs.

javascript
import escape from "lodash/escape";

const expr = "3 < 5 && 5 > 2";
console.log(escape(expr));

How It Works

Both < and & are encoded so the browser cannot misread comparison symbols as tag openers.

Example 5 — Round-trip with _.unescape()

Decode entities when you intentionally stored escaped text.

javascript
import escape from "lodash/escape";
import unescape from "lodash/unescape";

const original = "Tom & Jerry";
const encoded = escape(original);
const decoded = unescape(encoded);

console.log(encoded);
console.log(decoded);

How It Works

_.unescape() reverses entity encoding—use only on trusted content you intentionally encoded earlier.

🚀 Beyond the Basics

escape vs escapeRegExp and framework escaping.

Example 6 — escape vs escapeRegExp

Pick the right escape helper for HTML vs regular expressions.

javascript
import escape from "lodash/escape";
import escapeRegExp from "lodash/escapeRegExp";

const input = "a+b (test)";

console.log(escape(input));        // HTML entities
console.log(escapeRegExp(input)); // Regex metacharacters

How It Works

HTML escape protects DOM text nodes; escapeRegExp protects dynamic RegExp construction.

🧠 How _.escape() Works

1

Receive input string

Lodash coerces the argument to a string.

Input
2

Scan characters

Find & < > " ' and other mapped symbols.

Parse
3

Replace with entities

Substitute HTML entity equivalents (&lt;, etc.).

Transform
4

Return escaped copy

Original string unchanged; new safe string produced.

Output
=

Escaped string returned

Safe for insertion as HTML text when you cannot use textContent.

📝 Notes

  • _.escape() is for HTML text contexts—not URL or JavaScript string contexts.
  • Prefer element.textContent in the DOM when you only need plain text.
  • Pair with Content-Security-Policy and server-side validation for real XSS defense.
  • Use _.unescape() only on trusted encoded content.
  • Do not confuse with _.escapeRegExp().
  • Import lodash/escape for minimal bundles.

Conclusion

_.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.

💡 Best Practices

✅ Do

  • Escape user content before innerHTML insertion
  • Prefer textContent in DOM when possible
  • Combine with CSP and server validation
  • Import lodash/escape for tree-shaking
  • Document which fields are HTML vs plain text

❌ Don’t

  • Rely on escape alone for full XSS protection
  • Escape already-trusted HTML templates
  • Use escape for JavaScript or URL encoding
  • Double-escape without meaning to
  • Confuse escape with escapeRegExp

Key Takeaways

Knowledge Unlocked

Five things to remember about _.escape()

Use these points when rendering untrusted strings in HTML.

5
Core concepts
🛡 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.

Practice _.escape() in the Live Editor

Open the Try It editor, run the examples, and experiment with your own strings.

Open Try It editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful