Back to Functions

unescape

string

The inverse of escape; this method converts the HTML entities &, <, >, ", and ' in string to their corresponding characters.

Installation

Import
import { unescape } from '@tulx/utils';

Source Code

Implementation
/**
 * The inverse of escape; this method converts the HTML entities &, <, >, ", and ' in string to their corresponding characters.
 *
 * @param string - The string to unescape.
 * @returns Returns the unescaped string.
 *
 * @example
 * ```ts
 * unescape('fred, barney, & pebbles'); // 'fred, barney, & pebbles'
 * ```
 */
export function unescape(string: string): string {
  const map: Record<string, string> = {
    '&amp;': '&',
    '&lt;': '<',
    '&gt;': '>',
    '&quot;': '"',
    '&#39;': "'",
  };

  return string.replace(
    /&amp;|&lt;|&gt;|&quot;|&#39;/g,
    (entity) => map[entity] || entity
  );
}

Example

import { unescape } from '@tulx/utils';

unescape('fred, barney, &amp; pebbles'); // 'fred, barney, & pebbles'

Related Functions