Browse packages

Package · v0.18.0

html

Standard library HTML

Runtime support

  • Node
  • Deno
  • Bun
  • Browser

This module provides HTML text and quoted-attribute escaping for safely including untrusted strings in markup.

Installation#

bash
npm install @rcompat/html
bash
pnpm add @rcompat/html
bash
yarn add @rcompat/html
bash
bun add @rcompat/html

Usage#

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.

js
import HTML from "@rcompat/html";

HTML.escape("<script>alert('xss')</script>");
// "&lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;"

HTML.escape('Hello "world"');
// "Hello &quot;world&quot;"

HTML.escape("Tom & Jerry");
// "Tom &amp; Jerry"

Character escaping#

Character Escaped
& &amp;
< &lt;
> &gt;
" &quot;
' &#x27;

Examples#

Safe HTML templates#

js
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>&lt;script&gt;bad&lt;/script&gt;</h2>
//   <p>I&#x27;m a user</p>
// </div>

Escaping quoted attribute values#

js
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 &quot;results&quot;">Search &quot;results&quot;</span>

Form input display#

js
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">&lt;img src=x onerror=alert(1)&gt;</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.