escape ​
Converts characters with special meaning in HTML to safe entities.
typescript
const result = escape(str);Reference ​
escape(str) ​
Use escape when you want to safely insert text into HTML. It converts special characters like &, <, >, ", and ' to HTML entities to prevent XSS attacks and ensure HTML is displayed correctly.
typescript
import { escape } from 'es-toolkit/string';
// Handle basic HTML special characters
escape('<div>Hello World</div>'); // returns '<div>Hello World</div>'
escape('Tom & Jerry'); // returns 'Tom & Jerry'
escape('"Hello"'); // returns '"Hello"'
escape("'Hello'"); // returns ''Hello''It's essential for security when displaying user input in HTML.
typescript
import { escape } from 'es-toolkit/string';
// Handle user input
const userInput = '<script>alert("XSS")</script>';
const safeHtml = `<div>${escape(userInput)}</div>`;
// returns '<div><script>alert("XSS")</script></div>'
// Generate dynamic HTML
const title = 'Article "How to & Why"';
const html = `<h1>${escape(title)}</h1>`;
// returns '<h1>Article "How to & Why"</h1>'You can use it in templates or comment systems.
typescript
import { escape } from 'es-toolkit/string';
// Comment system
function renderComment(comment: string, author: string) {
return `
<div class="comment">
<strong>${escape(author)}</strong>: ${escape(comment)}
</div>
`;
}
// Usage example
const html = renderComment('I love <coding> & "programming"!', 'John Doe');
// returns '<div class="comment"><strong>John Doe</strong>: I love <coding> & "programming"!</div>'It's also useful when putting JSON strings in HTML attributes.
typescript
import { escape } from 'es-toolkit/string';
const data = { message: 'Hello & "welcome"' };
const jsonString = JSON.stringify(data);
const htmlAttribute = `<div data-info="${escape(jsonString)}"></div>`;
// returns '<div data-info="{"message":"Hello & \\"welcome\\""}"></div>'Parameters ​
str(string): The string to convert for safe use in HTML.
Returns ​
(string): Returns a new string with characters converted to HTML entities.

