

How to convert ArrayBuffer to and from String

ArrayBuffers are used to transport raw data and several new APIs rely on them, including WebSockets, Web Intents 2]( and WebWorkers. However, because they recently landed in the JavaScript world, sometimes they are misinterpreted or misused.


var bufView = new Uint16Array(buf);

One common practical question about ArrayBuffer is how to convert a String to an ArrayBuffer and vice-versa. Since an ArrayBuffer is, in fact, a byte array, this conversion requires that both ends agree on how to represent the characters in the String as bytes. You probably have seen this "agreement" before: it is the String's character encoding (and the usual "agreement terms" are, for example, Unicode UTF-16 and iso8859-1). Thus, supposing you and the other party have agreed on the UTF-16 encoding, the conversion code could be something like:

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
function str2ab(str) {
  var bufView = new Uint16Array(buf);
    bufView[i] = str.charCodeAt(i);
  return buf;

Note the use of Uint16Array. This is an ArrayBuffer view that aligns bytes of the ArrayBuffers as 16-bit elements. It doesn't handle the character encoding itself, which is handled as Unicode by String.fromCharCode and str.charCodeAt.

A popular StackOverflow question about this has a highly voted answer with a somewhat convoluted solution to the conversion: create a FileReader to act as a converter and feed a Blob containing the String into it. Although this method works, it has poor readability and I suspect it is slow. Since unfounded suspicions have driven many mistakes in the history of humanity, let's take a more scientific approach here. I have jsperf'ed the two methods and the result confirms my suspicion and you check out the demo here.
