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. 'α'
, ' '
).
import { Escaper } from 'html5-escape';
const escaper = new Escaper();
escaper.escapeData('< Abbott & Costello &me; "on first"');
// '< Abbott & Costello &me;'
escaper.escapeDoubleQuotedAttribute('< Abbott & Costello &me; "on first"');
// '< Abbott & Costello &me; "on first"e;'
Escape text for HTML5 documents.
The NUL character cannot be included in HTML documents. It is replaced with U+FFFD 'REPLACEMENT CHARACTER'.
options
Options (optional, default{}
)
- See: HTML 5.2, 8.2.4.1
Escape a text node
value
string text to escape
escaper.escapeData('< Abbott & Costello &me; "on first"');
// '< Abbott & Costello &me; "on first"'
Returns string escaped text
- See: HTML 5.2, 8.2.4.36
Escape an attribute value using double-quotes
value
string text to escape
escaper.escapeData('< Abbott & Costello &me; "on first"');
// '< Abbott & Costello &me; "on first"'
Returns string escaped text
- See: HTML 5.2, 8.2.4.37
Escape an attribute value using single-quotes
value
string text to escape
escaper.escapeData('< Abbott & Costello &me; "on first"');
// '< Abbott & Costello &me; "on first"'
Returns string escaped text
- See: HTML 5.2, 8.2.4.38
Escape an attribute value not using quotes
value
string text to escape
escaper.escapeData('< Abbott & Costello &me; "on first"');
// '<𠪻ott &Ȍostello &me; "on first"'
Returns string escaped text
Type: Object
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.