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

unescapeHTML

Unescapes HTML entities back to their original characters.

TypeScript
Copied!
1/**
2 * Unescapes HTML entities back to their original characters.
3 *
4 * @param str - The input string containing escaped HTML entities.
5 * @returns The unescaped string.
6 */
7export function unescapeHTML(str: string): string {
8  return str.replace(
9    /&(amp|lt|gt|quot|#39);/g,
10    (_, entity) =>
11      ({
12        amp: '&',
13        lt: '<',
14        gt: '>',
15        quot: '"',
16        '#39': "'",
17      }[entity] || entity)
18  );
19}
  • Reverses HTML Escaping

    Accurately restores previously escaped special characters, ensuring correct display of original content.

  • Targeted and Safe

    Only replaces known entities, avoiding overcorrection or unintended replacements.

  • Simple and Readable Implementation

    The use of a clear regex and a mapping object makes the logic easy to follow and maintain.

  • Lightweight Alternative to DOM Parsing

    Provides a faster and less resource-intensive solution than using innerHTML or a temporary DOM element.

Tests | Examples

TypeScript
Copied!
1test('unescapeHTML - unescapes all common HTML entities', () => {
2  expect(
3    unescapeHTML('&lt;div class=&quot;test&quot;&gt;Tom &amp; Jerry&lt;/div&gt;')
4  ).toBe('<div class="test">Tom & Jerry</div>');
5});
6
7test("unescapeHTML - unescapes single quote entity", () => {
8  expect(unescapeHTML('It&#39;s a test')).toBe("It's a test");
9});
10
11test('unescapeHTML - handles string without HTML entities', () => {
12  expect(unescapeHTML('No escaping needed')).toBe('No escaping needed');
13});
14
15test('unescapeHTML - handles empty string', () => {
16  expect(unescapeHTML('')).toBe('');
17});
18
19test('unescapeHTML - ignores unknown entities', () => {
20  expect(unescapeHTML('Fish &unknown; &lt; sea')).toBe('Fish &unknown; < sea');
21});

Common Use Cases

  • Rendering Stored User Input

    Convert stored HTML-safe text back to readable characters for display.

  • Processing Escaped Server Responses

    Decode escaped strings returned from APIs, databases, or logs before presenting them to users.

  • Reversing Sanitized Content for Editing

    Restore HTML characters when loading content into a WYSIWYG editor or input field.

  • Displaying Raw HTML Examples

    Decode strings when switching from code-preview to rendered mode in educational tools or documentation platforms.

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