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.

Browser supportโ€‹

APIChromeEdgeFirefoxSafariiOS SafariBaseline
TextEncoderโœ… 38+โœ… 79+โœ… 18+โœ… 10.1+โœ… 10.3+Widely available
TextDecoderโœ… 38+โœ… 79+โœ… 19+โœ… 10.1+โœ… 10.3+Widely available

โœ… supported ยท โ— partial ยท โŒ not supported ยท [n] see note. Generated from MDN browser-compat-data and web-features. caniuse: TextEncoder ยท TextDecoder

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.