Skip to main content

encodingapis

Encodes and decodes strings to and from UTF-8 bytes using TextEncoder/TextDecoder.

Import: @rtorcato/browser-common/encodingapis

๐Ÿ“– MDN: TextEncoder ยท ๐Ÿ“Š caniuse: textencoder

encodeUTF8/decodeUTF8 throw where TextEncoder/TextDecoder are unsupported โ€” guard with isTextEncoderAvailable()/isTextDecoderAvailable() first.

Unlike most of this library, this module is environment-agnostic: TextEncoder and TextDecoder are Node.js globals too, so it works outside the browser.

Exampleโ€‹

import {
isTextEncoderAvailable,
encodeUTF8,
decodeUTF8,
} from '@rtorcato/browser-common/encodingapis'

if (isTextEncoderAvailable()) {
const bytes = encodeUTF8('hello')
const text = decodeUTF8(bytes)
}

Exportsโ€‹

  • isTextEncoderAvailable() โ€” feature check for TextEncoder
  • isTextDecoderAvailable() โ€” feature check for TextDecoder
  • encodeUTF8(input) โ€” encodes a string into a Uint8Array
  • decodeUTF8(bytes) โ€” decodes a Uint8Array into a string

See the API reference for full signatures.