@rcompat/html
v0.18.0
Published
Standard library HTML
Readme
@rcompat/html
This module provides HTML text and quoted-attribute escaping for safely including untrusted strings in markup.
Installation
npm install @rcompat/htmlpnpm add @rcompat/htmlyarn add @rcompat/htmlbun add @rcompat/htmlUsage
escape
Escapes special characters for HTML text and quoted attribute values. This is one part of preventing Cross-Site Scripting (XSS), 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 |
|-----------|------------|
| & | & |
| < | < |
| > | > |
| " | " |
| ' | ' |
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 quoted attribute values
import HTML from "@rcompat/html";
function createLabel(text) {
const escaped = HTML.escape(text);
return `<span data-label="${escaped}">${escaped}</span>`;
}
createLabel('Search "results"');
// <span data-label="Search "results"">Search "results"</span>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 | |---------|-----------| | Browser | ✓ | | Node.js | ✓ | | Deno | ✓ | | Bun | ✓ |
No configuration required — just import and use.
License
MIT
Contributing
See CONTRIBUTING.md in the repository root.
