This post will discuss how to encode a string into a byte array in JavaScript.

Encoding a string into a byte array means converting each character of the string into a numerical value that represents its code point in a certain encoding scheme, such as UTF-8, UTF-16, or ASCII. A byte array is an array of 8-bit unsigned integers, which can store values from 0 to 255. There are several methods to encode a string into a byte array in JavaScript, depending on the encoding scheme and the environment. Here are some of the most common functions:

1. Using TextEncoder object

This method can be used to create a TextEncoder object that can encode strings into byte arrays using UTF-8 encoding, which is the most widely used and compatible encoding scheme for web applications. To use it, we need to create a new TextEncoder object and call its encode() function that takes a string as a parameter and returns a Uint8Array object, which is a typed array of 8-bit unsigned integers. Here’s an example:

Download  Run Code

 
This method works in both browsers and Node.js. However, it may not be supported by some older browsers. We can also use the TextDecoder object to decode the byte array back to a string using the same encoding scheme. Here’s an example:

Download  Run Code

2. Using Buffer.from() function

This function can be used to create a Node.js-specific Buffer object that contains the given string encoded in a specified encoding scheme. The syntax is Buffer.from(string[, encoding]), where string is the string to encode and encoding is the optional encoding scheme to use. The default encoding is ‘utf8’. The Buffer object can be accessed like an array of bytes. Here’s an example:

Download  Run Code

 
The Buffer object is similar to a byte array, but it is only available in Node.js and not in browsers. We can also use the Buffer.toString() function to decode the byte array back to a string using the same encoding scheme. Here’s an example:

Download  Run Code

3. Using charCodeAt() or codePointAt() functions

These functions can be used to get the numeric code point of each character in a string and store them in an array of bytes. The difference between these functions is that charCodeAt() returns a 16-bit value that represents the UTF-16 code unit at a given index, while codePointAt() returns a full Unicode code point that may consist of one or two code units. The idea is to use the split() function with empty string as the separator to get an array of characters from the string. Then to encode the characters into bytes, we need to invoke charCodeAt() or codePointAt() function. Here’s an example:

Download  Run Code

 
These functions work in both browsers and Node.js. However, they may not be able to handle characters that are outside the Basic Multilingual Plane (BMP), which are encoded using two code units (surrogate pairs) in UTF-16.

That’s all about encoding a string into a byte array in JavaScript.