Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

escapeHTML

Escapes special HTML characters to their corresponding HTML entities.

TypeScript
Copied!
1/**
2 * Escapes special HTML characters to their corresponding HTML entities.
3 *
4 * @param str - The input string to escape.
5 * @returns The escaped HTML string.
6 */
7export function escapeHTML(str: string): string {
8  return str.replace(/[&<>"']/g, char =>
9    ({
10      '&': '&amp;',
11      '<': '&lt;',
12      '>': '&gt;',
13      '"': '&quot;',
14      "'": '&#39;',
15    }[char] || char)
16  );
17}
  • Prevents HTML Injection

    Escapes dangerous characters that could otherwise be interpreted as HTML, reducing XSS attack vectors.

  • Minimal and Efficient

    Uses a concise replace operation with a fast lookup map, ensuring high performance even for large strings.

  • Preserves Original Text Structure

    Only transforms special characters, leaving all other content untouched and readable.

  • Works in All Environments

    Pure JavaScript implementation that doesn't depend on browser-specific APIs or libraries.

Tests | Examples

TypeScript
Copied!
1test('escapeHTML - escapes all basic HTML characters', () => {
2  expect(escapeHTML('<div class="test">Hello & Goodbye</div>')).toBe(
3    '&lt;div class=&quot;test&quot;&gt;Hello &amp; Goodbye&lt;/div&gt;'
4  );
5});
6
7test('escapeHTML - escapes single quote', () => {
8  expect(escapeHTML(`It's a test`)).toBe('It&#39;s a test');
9});
10
11test('escapeHTML - leaves string with no HTML characters unchanged', () => {
12  expect(escapeHTML('Plain text')).toBe('Plain text');
13});
14
15test('escapeHTML - handles empty string', () => {
16  expect(escapeHTML('')).toBe('');
17});
18
19test('escapeHTML - escapes only necessary characters', () => {
20  expect(escapeHTML('<a href="#">Link</a>')).toBe(
21    '&lt;a href=&quot;#&quot;&gt;Link&lt;/a&gt;'
22  );
23});

Common Use Cases

  • Sanitizing User Input

    Escape content before injecting it into the DOM to prevent code execution.

  • Displaying Raw HTML as Text

    Show actual HTML code snippets (e.g., <div>) in tutorials, documentation, or editors.

  • Log or Debug Output

    Safely render user-generated or server-returned HTML in a debug panel.

  • Templating Engines

    Prevent auto-rendered content in templated views from breaking the layout or introducing vulnerabilities.

Codebase: Utilities -> Encoding -> escapeHTML | Yevhen Klymentiev