unescapeHTML
Unescapes common HTML entities back into their corresponding characters.
1/**
2 * Unescapes common HTML entities back into their corresponding characters.
3 * Converts &, <, >, and " 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
1test('unescapeHTML - restores escaped HTML characters', () => {
2 expect(unescapeHTML('<div class="test">Hello & goodbye</div>'))
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('&<>"')).toBe('&<>"');
16});
17
18test('unescapeHTML - ignores unknown entities', () => {
19 expect(unescapeHTML('&unknown; <')).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.