No dependencies whatsoever. This package declares no dependencies or devDependencies.
Permalink to InstallationInstallation
Permalink to Quick TakeQuick Take
Permalink to ExamplesExamples
- Decode an attribute value
- Encode using stable named aliases
- Escape a quoted attribute value
- Encode without a named-reference table in bundled output
Purpose
Decode HTML character references, encode characters as references, or escape text for an HTML text node or quoted attribute. All transformations are synchronous and return a string.
import { decode, encode, escapeText } from "html-entity-codec";
console.log(decode("Cat & fiddle 😼🎻"));
// => "Cat & fiddle 😼🎻"
console.log(encode("© &", { useNamedReferences: true }));
// => "© &"
console.log(escapeText("<b>Cat & fiddle</b>"));
// => "<b>Cat & fiddle</b>"
Use decode() to read existing references. Use encode() when you want non-ASCII characters represented as references. Use escapeText() or escapeAttribute() when inserting a value into the corresponding HTML context.
API — decode()
Pass the input string and an optional options object. The function decodes named references such as &, decimal references such as ©, and hexadecimal references such as ©.
Decoding takes one pass. A reference produced by decoding is not decoded again:
import { decode } from "html-entity-codec";
console.log(decode("&copy;"));
// => "©"
console.log(decode("© © ©"));
// => "© © ©"
The decoding options are:
| Key | Type | Default | Description |
|---|---|---|---|
contextType: String Default: "text" | |||
context | String | "text" | Use "attribute" when decoding an attribute value. This rejects a named reference without a semicolon when an ASCII letter, digit, or = follows it. |
requireSemicolonType: Boolean Default: false | |||
requireSemicolon | Boolean | false | Set to true to leave references without a trailing semicolon unchanged. |
strictType: Boolean Default: false | |||
strict | Boolean | false | Set to true to throw a SyntaxError on character-reference parse errors. |
reportProgressFuncType: Function Default: undefined | |||
reportProgressFunc | Function | undefined | Receives progress percentages; see callbacks. |
reportCompletionFuncType: Function Default: undefined | |||
reportCompletionFunc | Function | undefined | Receives completion statistics; see callbacks. |
By default, numeric references and certain legacy named references can omit their semicolon. Names are case-sensitive; the decoder doesn’t repair mistyped names.
console.log(decode("©=1"));
// => "©=1"
console.log(decode("©=1", { context: "attribute" }));
// => "©=1"
console.log(decode("©", { requireSemicolon: true }));
// => "©"
In the default mode, a numeric reference for zero, a surrogate, or a value above U+10FFFF becomes the replacement character U+FFFD. Numeric references in the U+0080–U+009F range use HTML’s recovery mapping; for example, € becomes €. Unknown names without a recognised legacy prefix remain unchanged.
With strict: true, missing semicolons, unknown named references ending in a semicolon, numeric references without digits, and invalid or disallowed numeric values throw a SyntaxError. Strict checking takes precedence over requireSemicolon when a recognised reference is missing its semicolon. Attribute-context rejection still applies before a legacy name is accepted.
API — encode()
The default output uses hexadecimal references with uppercase digits. Set useNamedReferences: true to prefer named references where available, falling back to hexadecimal references otherwise.
import { encode } from "html-entity-codec";
console.log(encode("© & 😼"));
// => "© & 😼"
console.log(encode("© & 😼", { useNamedReferences: true }));
// => "© & 😼"
| Key | Type | Default | Description |
|---|---|---|---|
useNamedReferencesType: Boolean Default: false | |||
useNamedReferences | Boolean | false | Prefer stable named spellings over hexadecimal references. |
reportProgressFuncType: Function Default: undefined | |||
reportProgressFunc | Function | undefined | Receives progress percentages. |
reportCompletionFuncType: Function Default: undefined | |||
reportCompletionFunc | Function | undefined | Receives completion statistics. |
The encoder replaces double quotes, ampersands, apostrophes, angle brackets, backticks, and characters from U+00A0 upwards. It also encodes control characters in U+0001–U+0009, U+000B–U+000C, U+000E–U+001F, plus U+007F, U+0081, U+008D, U+008F, U+0090, and U+009D. Other characters, including ordinary spaces, line feeds, and carriage returns, remain unchanged.
Named aliases are chosen by shortest spelling, then preference for an entirely lowercase name, then ASCII lexical order. Named encoding can combine two code points into one reference. The literal pair fj remains unchanged, and tabs use numeric references.
Existing references are treated as input text: encode("&") returns "&amp;".
API — encodeNumeric()
Use this function when you always want hexadecimal references. It has the same character-selection policy as encode() with its default options, and lets bundlers omit the named-reference table when no other imports need it.
import { encodeNumeric } from "html-entity-codec";
console.log(encodeNumeric("© &"));
// => "© &"
The optional second argument accepts the callbacks.
API — escapeText()
Escape a value for an ordinary HTML text node. This replaces &, <, >, and the non-breaking space with &, <, >, and respectively. Quotes and other Unicode characters remain unchanged.
import { escapeText } from "html-entity-codec";
console.log(escapeText('"©" < 5 & 6'));
// => '"©" < 5 & 6'
The optional second argument accepts the callbacks. This function is for ordinary text nodes; it doesn’t provide escaping for raw-text elements such as script or style.
API — escapeAttribute()
Escape a value for a quoted HTML attribute. The caller adds the surrounding quotes and chooses the matching quote option.
| Key | Type | Default | Description |
|---|---|---|---|
quoteType: String Default: "double" | |||
quote | String | "double" | "double" escapes double quotes, "single" escapes apostrophes, and "both" escapes both. |
reportProgressFuncType: Function Default: undefined | |||
reportProgressFunc | Function | undefined | Receives progress percentages. |
reportCompletionFuncType: Function Default: undefined | |||
reportCompletionFunc | Function | undefined | Receives completion statistics. |
All modes replace ampersands with & and non-breaking spaces with . Double quotes become "; apostrophes become ' when selected by the option. Angle brackets remain unchanged.
import { escapeAttribute } from "html-entity-codec";
const value = 'Cat & "fiddle"';
console.log(`<span title="${escapeAttribute(value)}"></span>`);
// => '<span title="Cat & "fiddle""></span>'
console.log(escapeAttribute("Cat's fiddle", { quote: "single" }));
// => "Cat's fiddle"
Use this function for quoted attribute values. It doesn’t validate URLs or escape JavaScript or CSS inside attribute values. Both escape functions treat existing references as literal text, so escaping & produces &amp;.
API — scanReference()
Read one reference at a zero-based UTF-16 index in the original string. The index must point at its ampersand. The optional third argument accepts context, requireSemicolon, and strict, with the same defaults and behaviour as decode().
The result is { end, value }, where end is the exclusive UTF-16 offset in the original string and value is the decoded text. The function returns null if no reference is accepted at that index, including when the index is beyond the string.
import { scanReference } from "html-entity-codec";
console.log(scanReference("A & B", 2));
// => { end: 7, value: "&" }
console.log(scanReference("A & B", 0));
// => null
This function doesn’t search forwards and doesn’t accept progress or completion callbacks. It throws a TypeError if the index is negative or isn’t an integer.
Callbacks
All five string transformations accept these optional callbacks:
reportProgressFunc receives 0 at the start and 100 after a successful transformation. Intermediate percentages increase monotonically; don’t depend on receiving every percentage. Empty input also receives the start and finish notifications.
reportCompletionFunc runs after the final progress notification and receives:
Lengths count UTF-16 code units. replacements counts replacement operations: one decoded reference, one escaped character, or one encoded character or named pair. The transformed string remains the function’s return value.
import { decode } from "html-entity-codec";
const result = decode("A & B", {
reportCompletionFunc: ({ inputLength, outputLength, replacements }) => {
console.log(inputLength, outputLength, replacements);
// => 9 5 1
},
});
console.log(result);
// => "A & B"
Input validation
Every function requires a string as its first argument and throws a TypeError for other values. Empty strings are valid. These functions transform character references; they don’t parse or sanitise a complete HTML document.
API — version
You can import version:
API — types
The package exports the following TypeScript types:
| Type | Description |
|---|---|
ScanOptionsType: ScanOptions | |
ScanOptions | Context, semicolon, and strict parsing policies. |
DecodeOptionsType: DecodeOptions | |
DecodeOptions | Scanning policies and callbacks for decode(). |
EncodeOptionsType: EncodeOptions | |
EncodeOptions | Named-reference preference and callbacks for encode(). |
EscapeAttributeOptionsType: EscapeAttributeOptions | |
EscapeAttributeOptions | Quote selection and callbacks for escapeAttribute(). |
ObserveOptionsType: ObserveOptions | |
ObserveOptions | Shared progress and completion callbacks. |
CompletionType: Completion | |
Completion | Completion statistics. |
ReferenceType: Reference | |
Reference | Decoded value and exclusive source offset from scanReference(). |
import type {
Completion,
DecodeOptions,
EncodeOptions,
EscapeAttributeOptions,
ObserveOptions,
Reference,
ScanOptions,
} from "html-entity-codec";