Skip to content

escapeHtml function ​

Escapes the characters that have a meaning in HTML (& < > " '), to insert a text in markup.

ts
import { escapeHtml } from 'utils';

Signature ​

ts
export function escapeHtml(input: string): string

Parameters ​

NameDescription
inputThe text to escape.

Returns ​

The escaped text.

Example ​

ts
escapeHtml('<b>"Tom & Jerry"</b>'); // '&lt;b&gt;&quot;Tom &amp; Jerry&quot;&lt;/b&gt;'

Tests ​

Line coverage: 100 %.

  • ✅ escapes "<b>"Tom & Jerry"</b>"
  • ✅ escapes "it's"
  • ✅ escapes "plain text"
  • ✅ escapes "&"
  • ✅ escapes ""

Source ​

src/string/escape-html.ts (on GitHub)

Source code
ts
/**
 * Escapes the characters that have a meaning in HTML (`& < > " '`), to insert a text in markup.
 *
 * @param input - The text to escape.
 * @returns The escaped text.
 * @example
 * escapeHtml('<b>"Tom & Jerry"</b>'); // '&lt;b&gt;&quot;Tom &amp; Jerry&quot;&lt;/b&gt;'
 */
export function escapeHtml(input: string): string {
  return input
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;');
}
Test file
ts
import { escapeHtml } from './escape-html';

describe(escapeHtml, () => {
  it.for([
    ['<b>"Tom & Jerry"</b>', '&lt;b&gt;&quot;Tom &amp; Jerry&quot;&lt;/b&gt;'],
    ["it's", 'it&#39;s'],
    ['plain text', 'plain text'],
    ['&amp;', '&amp;amp;'],
    ['', ''],
  ] as const)('escapes %j', ([input, expected]) => {
    expect(escapeHtml(input)).toBe(expected);
  });
});

Keywords: escape, html, strings, function

Generated from the JSDoc of the sources.