Skip to main content

escape()

escape(str): string

Escapes HTML special characters to their corresponding entities.

note

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>');   // => '&lt;div&gt;'
escape('a & b'); // => 'a &amp; b'
escape('"hello"'); // => '&quot;hello&quot;'
escape('<script>alert("XSS")</script>');
// => '&lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;'

How it works?โ€‹

Escapes HTML special characters to their corresponding entities. Essential for XSS prevention.

Character Mappingโ€‹

CharacterEntity
&&amp;
<&lt;
>&gt;
"&quot;
'&#39;

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>');
// '&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;'

Sanitize user commentsโ€‹

Escape HTML entities in user-submitted content before display.

const comment = escape('I <3 this product & service!');
// 'I &lt;3 this product &amp; 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 });