How to Convert a JavaScript String to a Byte Array?

In JavaScript, you can convert a string to an array of bytes by using the TextEncoder API, for example, in the following way:

function toBytesArray(str) {
  const encoder = new TextEncoder();
  return encoder.encode(str);

console.log(toBytesArray('🦊')); // Uint8Array[240, 159, 166, 138]
console.log(toBytesArray('こんにちは')); // Uint8Array[227, 129, 147, 227, 130, 147, 227, 129, 171, 227, 129, 161, 227, 129, 175]
console.log(toBytesArray('foobar')); // Uint8Array[102, 111, 111, 98, 97, 114]

In this example, the TextEncoder.encode() method takes a string as input and returns a Uint8Array object containing the UTF-8 encoded bytes of the string. You can then use this byte array for further processing, such as sending it over a network, storing it in a file, or performing other processing tasks that require a byte array representation of the string.

The TextEncoder.encode() method can encode any valid JavaScript string, including multibyte strings, into a byte array representation of the string. For ASCII strings that contain single-byte characters, each character is split into a sequence of 8 bits. For non-ASCII strings that contain multibyte characters, the conversion to a byte array requires a more complex encoding process, such as UTF-8, which can encode characters that require more than one byte.

The TextEncoder API is very well-supported in modern browsers. For older browsers so you may need to include a polyfill.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.