@prexjs/escape-html
v1.0.0
Published
Escape HTML special characters in strings to prevent cross-site scripting (XSS).
Readme
@prexjs/escape-html
Escape HTML special characters in strings to prevent cross-site scripting (XSS).
@prexjs/escape-html is an extremely fast, lightweight utility for escaping string characters (", ', &, <, >) into safe HTML entities to protect web applications against Cross-Site Scripting (XSS).
Features
- Escapes
",',&,<, and>characters into corresponding HTML character entities (",',&,<,>). - Optimized regex fast-path returns unmodified strings without copying when no escapable characters are present.
- High-performance single-pass character code loop.
- Dual ES Module (
.mjs) and CommonJS (.cjs) support with TypeScript definitions. - Zero runtime dependencies.
Installation
Install using your preferred package manager:
# npm
npm install @prexjs/escape-html
# pnpm
pnpm add @prexjs/escape-html
# Yarn
yarn add @prexjs/escape-html
# Bun
bun add @prexjs/escape-htmlQuick start
import escapeHtml from '@prexjs/escape-html';
const userInput = '<script>alert("XSS")</script>';
const safeHtml = escapeHtml(userInput);
console.log(safeHtml);
// '<script>alert("XSS")</script>'Both default and named exports are supported:
import escapeHtml, { escapeHtml as namedEscapeHtml } from '@prexjs/escape-html';Examples
Escaping attributes and content
import escapeHtml from '@prexjs/escape-html';
const title = 'Sorabh & Friends\' Adventures';
const tag = `<h1 title="${escapeHtml(title)}">${escapeHtml(title)}</h1>`;
console.log(tag);
// '<h1 title="Sorabh & Friends' Adventures">Sorabh & Friends' Adventures</h1>'Compatibility
@prexjs/escape-html is designed for JavaScript and TypeScript projects. It runs in any modern JavaScript runtime (Node.js, Deno, Bun, browser) without external dependencies.
License
This project is licensed under the MIT License. See LICENSE for the full license text.
Related projects
- prex.js — prex.js monorepo and ecosystem.
