/html5-escape

Escape strings for HTML5 in a pleasing manner

Primary LanguageTypeScript

html5-escape

Escape strings for HTML5 in a pleasing manner.

While it is relative unchallenging to sufficiently escape strings, this library escapes minimally. E.g.

const string = 'a && b';

/* sufficiently */
const Serializer = require('parse5/lib/serializer');
Serializer.escapeString(string);
// 'a && b'

/* minimally */
const { Escaper } = require('html5-escape');
new Escaper().escapeData(string);
// 'a && b'

html5-escape can optionally encode control or non-ASCII characters. It preferentially uses named entities when available (e.g. 'α', ' ').

Usage

import { Escaper } from 'html5-escape';

const escaper = new Escaper();
escaper.escapeData('< Abbott & Costello &me; "on first"');
// '&lt; Abbott & Costello &amp;me;'
escaper.escapeDoubleQuotedAttribute('< Abbott & Costello &me; "on first"');
// '< Abbott & Costello &amp;me; &quot;on first&quote;'

API

Escaper

Escape text for HTML5 documents.

The NUL character cannot be included in HTML documents. It is replaced with U+FFFD 'REPLACEMENT CHARACTER'.

Parameters

  • options Options (optional, default {})

escapeData

Escape a text node

Parameters
Examples
escaper.escapeData('< Abbott & Costello &me; "on first"');
// '&lt; Abbott & Costello &amp;me; "on first"'

Returns string escaped text

escapeDoubleQuotedAttribute

Escape an attribute value using double-quotes

Parameters
Examples
escaper.escapeData('< Abbott & Costello &me; "on first"');
// '< Abbott & Costello &amp;me; &quot;on first&quot;'

Returns string escaped text

escapeSingleQuotedAttribute

Escape an attribute value using single-quotes

Parameters
Examples
escaper.escapeData('< Abbott & Costello &me; "on first"');
// '< Abbott & Costello &amp;me; "on first"'

Returns string escaped text

escapeUnquotedAttribute

Escape an attribute value not using quotes

Parameters
Examples
escaper.escapeData('< Abbott & Costello &me; "on first"');
// '&lt;&#x20Abbott&#x20&&#x20Costello&#x20&amp;me;&#x20&quot;on first&quot;'

Returns string escaped text

Options

Type: Object

Properties

  • escapeRanges string? zero or more of 'control', 'nonbreaking-space', and 'non-ascii'. Defaults to ['control', 'nonbreaking-space']
  • escapeBase string? either 10 or 16. Defaults to 16.
  • forceEscape boolean? whether to coerce characters to alternative forms if necessary to escape them. Defaults to true.