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 common HTML entities back into their corresponding characters.

TypeScript
Copied!
1/**
2 * Unescapes common HTML entities back into their corresponding characters.
3 * Converts &amp;, &lt;, &gt;, and &quot; back into &, <, >, and ".
4 *
5 * @param str - The input string containing HTML entities.
6 * @returns A string with unescaped HTML characters.
7 */
8export function unescapeHTML(str: string): string {
9  return str.replace(/&(amp|lt|gt|quot);/g, (_, entity) => (
10    {
11      amp: '&',
12      lt: '<',
13      gt: '>',
14      quot: '"',
15    }[entity] || entity
16  ));
17}
  • Restores Original Content

    Converts common HTML entities (&, <, >, ") back to their readable characters (&, <, >, "), which is essential when interpreting or displaying previously escaped text.

  • Lightweight and Fast

    Uses a single regular expression and simple mapping for fast and efficient decoding, without any external dependencies.

  • Safe for Controlled Inputs

    Effective in environments where input is known to be clean and only needs limited unescaping (e.g., after escapeHTML).

  • Customizable

    Easy to extend to include more entities if needed (e.g., ',  ).

Tests | Examples

TypeScript
Copied!
1test('unescapeHTML - restores escaped HTML characters', () => {
2  expect(unescapeHTML('&lt;div class=&quot;test&quot;&gt;Hello &amp; goodbye&lt;/div&gt;'))
3    .toBe('<div class="test">Hello & goodbye</div>');
4});
5
6test('unescapeHTML - leaves plain text untouched', () => {
7  expect(unescapeHTML('Just a normal sentence')).toBe('Just a normal sentence');
8});
9
10test('unescapeHTML - handles empty string', () => {
11  expect(unescapeHTML('')).toBe('');
12});
13
14test('unescapeHTML - handles only escaped characters', () => {
15  expect(unescapeHTML('&amp;&lt;&gt;&quot;')).toBe('&<>"');
16});
17
18test('unescapeHTML - ignores unknown entities', () => {
19  expect(unescapeHTML('&unknown; &lt;')).toBe('&unknown; <');
20});

Common Use Cases

  • Reversing Escaped HTML for Display or Processing

    Unescape text that was previously processed by escapeHTML or similar logic, for use in plaintext contexts or editors.

  • Reading Stored HTML as Text

    Decode values retrieved from storage or APIs where content is stored as escaped HTML strings.

  • Converting Safe Strings Back for Editors

    Transform safe strings back into their original form before inserting them into WYSIWYG editors, form fields, or text areas.

  • Parsing Lightweight Markup

    Useful in markdown or template engines that need to display clean content to users without showing entity codes.

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