Escape string for use in HTML to prevent XSS attacks
npx @tessl/cli install tessl/npm-escape-html@1.0.0Escape HTML is a lightweight JavaScript utility library for escaping special HTML characters in strings to prevent XSS attacks and ensure safe HTML output. It focuses on high-performance string processing to escape five critical HTML characters and is designed for maximum reusability across web applications.
npm install escape-htmlconst escapeHtml = require('escape-html');For component.js (legacy support):
var escapeHtml = require('escape-html');const escapeHtml = require('escape-html');
// Escape special HTML characters
const userInput = 'Hello <script>alert("XSS")</script> & "quotes"';
const safeHtml = escapeHtml(userInput);
console.log(safeHtml);
// Output: Hello <script>alert("XSS")</script> & "quotes"
// Works with any input type (coerced to string)
const numericInput = escapeHtml(123);
console.log(numericInput); // "123"
// Handles undefined and null
const emptyInput = escapeHtml(null);
console.log(emptyInput); // "null"Escapes special characters in the given string for safe insertion into HTML content.
/**
* Escape special characters in the given string of html.
*
* @param {any} string - The input value to escape for HTML (will be coerced to string)
* @returns {string} The escaped HTML string
*/
function escapeHtml(string);Escaped Characters:
" (double quote) → "& (ampersand) → &' (single quote) → '< (less-than) → <> (greater-than) → >Performance Characteristics:
Usage Examples:
const escapeHtml = require('escape-html');
// Basic HTML escaping
const userComment = 'I love <strong>bold</strong> text & "quotes"!';
const safeComment = escapeHtml(userComment);
// Result: I love <strong>bold</strong> text & "quotes"!
// Template integration
function renderTemplate(data) {
return `<div class="comment">${escapeHtml(data.userInput)}</div>`;
}
// Safe attribute values
const title = 'Product "A" & Company\'s <special> item';
const safeTitle = escapeHtml(title);
// Use in: <img alt="${safeTitle}" />
// Type coercion examples
escapeHtml(42); // "42"
escapeHtml(true); // "true"
escapeHtml(undefined); // "undefined"
escapeHtml({ a: 1 }); // "[object Object]"Common Use Cases: