
fast-escape-html is a tiny, blazing-fast HTML escaping library that helps you securely encode HTML characters in both Node.js and browser.
Features:
- Superior performance: Outperforms Rust-based HTML escaping libraries with real-world HTML content.
- Single-pass processing: Processes input strings once, preventing double-encoding vulnerabilities.
- Complete test coverage: 100% test coverage ensures reliable behavior across edge cases.
- Safe unescaping: Avoids multiple replacements that lead to XSS risks.
Use Cases
- User-generated content display: Safely render user comments, forum posts, or form submissions in web applications without XSS risks.
- Template engine integration: Escape dynamic content in custom template systems or server-side rendering frameworks.
- API response sanitization: Clean HTML characters from API responses before sending data to frontend applications.
- Content management systems: Process and display article content, page descriptions, or metadata that may contain HTML characters.
How to use it:
1. Install fast-escape-html using your preferred package manager:
# Yarn $ yarn add fast-escape-html # NPM $ npm install fast-escape-html # PNPM $ pnpm install fast-escape-html
2. Import the library functions and start escaping HTML content:
import { escapeHTML, unescapeHTML } from 'fast-escape-html';// OR
<script type="module">
import { escapeHTML, unescapeHTML } from './dist/es/index.mjs';
</script>// Escape HTML characters for safe display
const userInput = '<script>alert("malicious code")</script>';
const safeOutput = escapeHTML(userInput);
console.log(safeOutput);
// Output: <script>alert("malicious code")</script>
// Unescape previously escaped HTML
const escapedContent = '<h1>CSSScript.com</h1>';
const originalContent = unescapeHTML(escapedContent);
console.log(originalContent);
// Output: <h1>CSSScript.com</h1>3. For applications processing multiple strings, you can create utility functions:
import { escapeHTML } from 'fast-escape-html';
// Process user comments before database storage
function sanitizeComment(comment) {
return escapeHTML(comment.trim());
}
// Bulk process an array of content
function escapeMultipleStrings(strings) {
return strings.map(str => escapeHTML(str));
}
const comments = ['<b>Great post!</b>', 'Love the <em>examples</em>'];
const safeComments = escapeMultipleStrings(comments);How it works:
The escaping function first uses a regular expression to locate the initial HTML character in the input string. If no HTML characters exist, it returns the original string immediately to avoid unnecessary processing overhead.
When HTML characters are detected, the function switches to a character-by-character processing mode using charCodeAt for maximum speed. The algorithm maintains separate variables for the HTML output, the current position, and the last processed index. This approach minimizes string concatenation operations and reduces memory allocation during processing.
The character mapping uses a switch statement ordered by frequency of occurrence in real-world HTML content. The library prioritizes less-than symbols, followed by greater-than symbols, double quotes, single quotes, and ampersands. This ordering reduces the average number of comparisons needed during processing.
For unescaping, the library employs a global regular expression with a lookup table created using Object.create(null) for optimal property access performance. The unescaping process handles both named entities and numeric character references, supporting common variations developers encounter in real applications.
FAQs:
Q: Can I use fast-escape-html to sanitize HTML from untrusted sources?
A: fast-escape-html escapes HTML characters but doesn’t provide full HTML sanitization. For untrusted HTML content that needs to preserve some markup, use dedicated sanitization libraries like DOMPurify. fast-escape-html works best when you need to display text content that may contain HTML characters but shouldn’t render as markup.
Q: Why is fast-escape-html faster than Rust-based alternatives?
A: The performance advantage comes from the single-pass algorithm and JavaScript engine optimizations. While Rust has inherent speed advantages, the overhead of calling into WebAssembly or native modules often negates these benefits for typical HTML escaping tasks. fast-escape-html’s pure JavaScript approach avoids this overhead.
Q: Does the library handle Unicode characters properly?
A: Yes, fast-escape-html processes Unicode characters correctly since it only targets specific HTML characters (&, <, >, “, ‘).
Q: Can I customize which characters get escaped?
A: The library focuses on the standard HTML characters that pose XSS risks. If you need custom character escaping, you’ll need to implement your own solution or use a more configurable library like he. The fixed character set keeps fast-escape-html simple and secure.







