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 });
Sanitize chat messages in real-timeβ
Escape user messages before rendering in a live chat interface. Critical for chat apps, comment sections, and any real-time messaging UI.
ws.on("message", (raw) => {
const data = JSON.parse(raw);
const safeMessage = escape(data.text);
appendMessage({
author: escape(data.username),
content: safeMessage,
timestamp: data.timestamp,
});
});
Escape dynamic content in SSR templatesβ
Prevent XSS when injecting dynamic data into server-rendered HTML. Essential for SSR frameworks and server-side template engines.
const renderProductPage = (product) => `
<div class="product">
<h1>${escape(product.name)}</h1>
<p class="description">${escape(product.description)}</p>
<span class="price">${escape(String(product.price))}</span>
</div>
`;