Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk3 min

JavaScript Text to UTF-8 Bytes: Encode and Decode Correctly

Use TextEncoder and TextDecoder to convert JavaScript strings to UTF-8 bytes and back, with a clear distinction between bytes and Base64 text.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use TextEncoder to convert a JavaScript string to UTF-8 bytes, then TextDecoder to turn those bytes back into text. The bytes are a Uint8Array; they are not the same as a Base64 string or a binary-looking string of 0s and 1s.

Convert text to bytes and back

JavaScript strings are text, not byte arrays. To represent text as bytes, choose a character encoding. UTF-8 is the practical default for exchanging new text between systems.

As an Amazon Associate I earn from qualifying purchases.

const text = "Hello, 🌍";
const bytes = new TextEncoder().encode(text);

console.log(bytes); // Uint8Array containing UTF-8 bytes

const decoded = new TextDecoder().decode(bytes);
console.log(decoded); // "Hello, 🌍"

TextEncoder.encode() takes a string and returns a Uint8Array encoded as UTF-8, as documented by MDN. The WHATWG Encoding Standard defines the browser encoding APIs. TextDecoder.decode() converts bytes back to a string; its default encoding is UTF-8, and MDN documents the method at TextDecoder.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When an API specifically requires an ArrayBuffer, use the byte array’s underlying buffer: bytes.buffer. A Uint8Array is a view over that storage and is often the more convenient representation for byte-by-byte work.

Bytes, binary strings, and Base64 are different

“Binary” can mean raw bytes, or it can mean text used to represent bytes. The code above produces raw UTF-8 bytes. Base64, by contrast, encodes bytes as ASCII text for transport or embedding; it is neither raw binary data nor encryption.

The browser functions btoa() and atob() operate on binary strings: each character represents one byte. Passing arbitrary Unicode text directly to btoa() can fail because characters outside the byte range cannot be represented that way. For Unicode text, first encode it to UTF-8 bytes, then convert those byte values to a binary string for Base64 encoding. MDN describes this behavior and pattern on its btoa() page.

function bytesToBase64(bytes) {
  const binaryString = Array.from(
    bytes,
    byte => String.fromCodePoint(byte)
  ).join("");
  return btoa(binaryString);
}

function base64ToBytes(base64) {
  const binaryString = atob(base64);
  return Uint8Array.from(
    binaryString,
    char => char.codePointAt(0)
  );
}

const text = "A café 🦄";
const bytes = new TextEncoder().encode(text);
const base64 = bytesToBase64(bytes);
const restored = new TextDecoder().decode(base64ToBytes(base64));

console.log(base64);
console.log(restored); // "A café 🦄"

atob() returns a binary string containing the decoded byte values, not decoded Unicode text. The example turns those values back into a Uint8Array and then decodes the UTF-8 bytes. MDN documents atob() and notes that newer runtimes may offer Base64 methods on typed arrays; check compatibility for your target before using those methods.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Handle malformed bytes deliberately

By default, decoding malformed UTF-8 uses replacement behavior: invalid sequences can become replacement characters in the resulting string. If silent substitution would hide corrupted or incorrectly interpreted data, request fatal decoding instead:

const decoder = new TextDecoder("utf-8", { fatal: true });

try {
  const text = decoder.decode(bytes);
  console.log(text);
} catch (error) {
  console.error("Could not decode the bytes as valid UTF-8", error);
}

With fatal: true, invalid input causes a decoding error rather than replacement. A failure can mean the bytes are malformed, or that UTF-8 is not the encoding used to create them. The WHATWG Encoding Standard specifies both modes.

Choose the conversion for the data you have

  • Need bytes for an API, file, or protocol: use TextEncoder and pass its Uint8Array, or bytes.buffer if the API specifically expects an ArrayBuffer.
  • Need text back from UTF-8 bytes: use TextDecoder; its default encoding is UTF-8.
  • Need a printable text representation of bytes: use Base64, encoding Unicode text to UTF-8 bytes first.
  • Have bytes in a known non-UTF-8 encoding: decode with the correct encoding rather than assuming UTF-8. The decoder’s encoding must match the bytes’ source.
  • Need decoding to reject invalid input: construct TextDecoder("utf-8", { fatal: true }).
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Browser and runtime support

The Encoding API is defined by WHATWG. MDN marks TextEncoder and TextDecoder widely available in browsers, with browser availability dating to January 2020; see the compatibility notes on the encode() and TextDecoder references. That browser compatibility information does not establish support in every embedded JavaScript runtime, so check the documentation for the specific runtime you deploy to.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.