Skip to content

isValidText

isValidText(bytes, encoding): boolean

Defined in: packages/core/src/buffer/text/is-valid-text.ts:26

Whether bytes is valid text in encoding: whether decoding it would succeed without a single replacement character.

Use it to test candidate encodings when guessing which one a byte string uses; use decodeText with fatal when the text itself is wanted. Always true for "latin1", "ascii" and "windows-1252", where every byte decodes.

Time complexity: O(n) in bytes.length. Memory: O(n) for the decoded string, discarded.

Uint8Array

The bytes to test.

TextDecodingName

The candidate encoding.

boolean

Whether every byte decodes.

isValidText(new Uint8Array([0xc3, 0xa9]), "utf-8"); // true
isValidText(new Uint8Array([0xe9]), "utf-8"); // false

For "shift_jis" where the runtime’s TextDecoder lacks it.