escape()
escape(
str):string
Escapes HTML special characters to their corresponding entities.
Escapes &, <, >, ", and '. Essential for XSS prevention.
Parameters
str: string
The string to escape.
Returns: string
The escaped string.
See Also
unescape for the inverse operation.
Since
2.0.0
Performance
O(n) time where n is string length. Single regex pass with object lookup.
Also known as
escape (Lodash, es-toolkit) · escapeHTML (Radashi) · escapeHtml (Modern Dash) · ❌ (Remeda, Ramda, Effect, Antfu)
Example
escape('<div>'); // => '<div>'
escape('a & b'); // => 'a & b'
escape('"hello"'); // => '"hello"'
escape('<script>alert("XSS")</script>');
// => '<script>alert("XSS")</script>'
How it works?
Escapes HTML special characters to their corresponding entities. Essential for XSS prevention.
Character Mapping
| Character | Entity |
|---|---|
& | & |
< | < |
> | > |
" | " |
' | ' |
XSS Prevention
Roundtrip with unescape
Use Cases
Prevent XSS 📌
Escape unsafe characters in strings before rendering to HTML. Critical for security when displaying user-generated content.
const safeHtml = escape('<script>alert("xss")</script>');
// '<script>alert("xss")</script>'
Sanitize user comments
Escape HTML entities in user-submitted content before display.
const comment = escape('I <3 this product & service!');
// 'I <3 this product & service!'
Escape user input in HTML email templates
Prevent HTML injection when inserting user-provided data into email templates.
const html = `
<h1>Hello ${escape(userName)}</h1>
<p>Your message: ${escape(userMessage)}</p>
`;
sendEmail({ to: recipient, html });