JavaScript program to convert a string to array buffer

In this tutorial, we will see a JavaScript program to convert a string to an array buffer.

Assume we have to perform the request payload encryption and for that, we have to import the public key, to make use of this public key we have to convert its string to an array buffer after base24 decoding it.

To convert the string, we will first create a unit8Array of the strings length size and then using the codePointAt method of string, get the Unicode of each character.

const stringToArrayBuffer = (string) => {
  let byteArray = new Uint8Array(string.length);
  for(var i=0; i < string.length; i++) {
    byteArray[i] = string.codePointAt(i);
  }
  return byteArray;
}

Here for testing, we are using the inverse method, arrayBufferToString that converts back the array buffer to a string.

console.log(arrayBufferToString(stringToArrayBuffer("abcd")));
// "abcd"

We have first converted the string to array buffer and back to the string.