Function: encodeText()
encodeText(
input,enc?):string
Encode-safe direction: escape an arbitrary string so it can be placed in
an HL7 field as data without ever breaking framing. Every reserved character
: the escape char (escaped first, so decoding is unambiguous), the field,
component, subcomponent, and repetition separators, the declared truncation
char, and the framing-critical \n/\r: is replaced by its escape
sequence, so the value cannot inject a delimiter or forge a component /
subcomponent / repetition boundary.
The hard invariant, property-tested over arbitrary strings:
decodeText(encodeText(s, enc), enc) === s, and a message field carrying
encodeText(s) cannot forge a component / subcomponent / repetition
boundary or break framing: the value never escapes its field.
Two caveats are inherent to HL7 field encoding, not to this codec, and apply
to whole-field re-parse (they do not weaken the no-injection guarantee):
the two-character string "" is HL7's explicit-null token, so a field whose
entire value is "" re-parses as null; and the default parser trims field
whitespace, so a value with leading/trailing spaces re-parses trimmed. Encode
such values into a component/subcomponent position, or parse with trimming
off, to preserve them exactly.
Parameters
input
string
the arbitrary string to encode.
enc?
EncodingCharacters = DEFAULT_ENCODING_CHARACTERS
encoding characters; defaults to the HL7 standard |^~\&.
Returns
string
the spec-clean, delimiter-safe field body.
Example
import { encodeText, parseHL7 } from "@cosyte/hl7";
// A value full of delimiters cannot break out of its field:
const hostile = "a|b^c~d\\e&f";
const body = encodeText(hostile); // "a\\F\\b\\S\\c\\R\\d\\E\\e\\T\\f"
const msg = parseHL7(`MSH|^~\\&|A|B|C|D|20260101||ADT^A01|1|P|2.5\rNTE|1||${body}`);
msg.segments("NTE")[0]?.field(3).value === hostile; // true: round-trips exactly