@rcompat/html
v0.9.0
Published
Standard library HTML
Readme
@rcompat/html
HTML utilities for JavaScript runtimes.
What is @rcompat/html?
A cross-runtime module providing HTML handling utilities, including escaping for XSS prevention. Works consistently across Node, Deno, and Bun.
Installation
npm install @rcompat/htmlpnpm add @rcompat/htmlyarn add @rcompat/htmlbun add @rcompat/htmlUsage
escape
Escapes HTML special characters to prevent Cross-Site Scripting (XSS) attacks. Based on OWASP recommendations.
import HTML from "@rcompat/html";
HTML.escape("<script>alert('xss')</script>");
// "<script>alert('xss')</script>"
HTML.escape('Hello "world"');
// "Hello "world""
HTML.escape("Tom & Jerry");
// "Tom & Jerry"Character escaping
| Character | Escaped |
|-----------|------------|
| & | & |
| < | < |
| > | > |
| " | " |
| ' | ' |
API Reference
escape(input)
declare function escape(input: string): string;Escapes HTML special characters in a string.
| Parameter | Type | Description |
|-----------|----------|--------------------------|
| input | string | The string to escape |
Returns: The escaped string safe for HTML insertion.
Examples
Safe HTML templates
import HTML from "@rcompat/html";
function renderUser(user) {
return `
<div class="user">
<h2>${HTML.escape(user.name)}</h2>
<p>${HTML.escape(user.bio)}</p>
</div>
`;
}
renderUser({ name: "<script>bad</script>", bio: "I'm a user" });
// <div class="user">
// <h2><script>bad</script></h2>
// <p>I'm a user</p>
// </div>Escaping attribute values
import HTML from "@rcompat/html";
const { escape } = HTML;
function createLink(url, text) {
return `<a href="${escape(url)}" title="${escape(text)}">${escape(text)}</a>`;
}
createLink("/search?q=a&b=c", 'Search "results"');
// <a href="/search?q=a&b=c" title="Search "results"">Search "results"</a>Form input display
import HTML from "@rcompat/html";
function displayComment(comment) {
return `<div class="comment">${HTML.escape(comment.text)}</div>`;
}
// Malicious input is safely escaped
displayComment({ text: "<img src=x onerror=alert(1)>" });
// <div class="comment"><img src=x onerror=alert(1)></div>Cross-Runtime Compatibility
| Runtime | Supported | |---------|-----------| | Node.js | ✓ | | Deno | ✓ | | Bun | ✓ |
No configuration required — just import and use.
License
MIT
Contributing
See CONTRIBUTING.md in the repository root.
