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 in a string to prevent injection.

TypeScript
Copied!
1/**
2 * Escapes special HTML characters in a string to prevent injection.
3 * Converts &, <, >, and " into their corresponding HTML entities.
4 *
5 * @param str - The input string to escape.
6 * @returns A string with HTML-escaped characters.
7 */
8export function escapeHTML(str: string): string {
9  return str.replace(/[&<>"]/g, tag => (
10    {
11      '&': '&amp;',
12      '<': '&lt;',
13      '>': '&gt;',
14      '"': '&quot;',
15    }[tag] || tag
16  ));
17}
  • Protects Against XSS

    Escapes critical characters (&, <, >, ") commonly used in Cross-Site Scripting (XSS) attacks, making it safer to render user input in HTML contexts.

  • Lightweight and Dependency-Free

    A compact solution that doesn't rely on external libraries, ideal for small applications or performance-sensitive environments.

  • Simple and Readable

    The mapping logic is easy to understand and customize if more characters need to be escaped.

  • Safe for Rendering in Browsers

    Prevents accidental interpretation of text as HTML or JavaScript in the DOM.

Tests | Examples

TypeScript
Copied!
1test('escapeHTML - escapes common HTML characters', () => {
2  expect(escapeHTML('<div class="test">Hello & welcome!</div>')).toBe(
3    '&lt;div class=&quot;test&quot;&gt;Hello &amp; welcome!&lt;/div&gt;'
4  );
5});
6
7test('escapeHTML - leaves normal text unchanged', () => {
8  expect(escapeHTML('Just text with no tags')).toBe('Just text with no tags');
9});
10
11test('escapeHTML - handles empty string', () => {
12  expect(escapeHTML('')).toBe('');
13});
14
15test('escapeHTML - handles only special characters', () => {
16  expect(escapeHTML('&<>"')).toBe('&amp;&lt;&gt;&quot;');
17});
18
19test('escapeHTML - ignores unlisted characters', () => {
20  expect(escapeHTML("It's > than 3 & < than 10")).toBe(
21    'It\'s &gt; than 3 &amp; &lt; than 10'
22  );
23});

Common Use Cases

  • Rendering User Input

    Safely display user-generated content in the browser without risking script injection.

  • Sanitizing Strings Before Insertion

    Use before inserting text into innerHTML, attributes, or templates to avoid breaking markup.

  • Email Templates and Reports

    Escape dynamic content before injecting it into HTML-based email bodies or exported documents.

  • Preprocessing in Static Site Generators

    Clean text content before writing to HTML files during static site compilation.

  • Storing Raw HTML in Text Format

    Encode HTML characters to store or transmit raw HTML as safe plain text.

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