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 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 |
|---|---|
& |
& |
< |
< |
> |
> |
" |
" |
' |
' |
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 string encoded for HTML text or a quoted attribute value.
HTML encoding is context-specific. This function does not make input safe for JavaScript, CSS, unquoted attributes, or URL protocols. Validate URLs and other structured values before encoding them.
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 |
|---|---|
| Node.js | ✓ |
| Deno | ✓ |
| Bun | ✓ |
No configuration required — just import and use.
License#
MIT
Contributing#
See CONTRIBUTING.md in the repository root.