Update 2016 - five years on there are now new methods in the specs (see support below) to convert between strings and typed arrays using proper encoding.

##TextEncoder

The TextEncoder represents:

The TextEncoder interface represents an encoder for a specific method, that is a specific character encoding, liarraybufferke utf-8, iso-8859-2, koi8, cp1261, gbk, ... An encoder takes a stream of code points as input and emits a stream of bytes.

Change note since the above was written: (ibid.)

Note: Firefox, Chrome and Opera used to have support for encoding types other than utf-8 (such as utf-16, iso-8859-2, koi8, cp1261, and gbk). As of Firefox 48 [...], Chrome 54 [...] and Opera 41, no other encoding types are available other than utf-8, in order to match the spec.*

*) Updated specs (W3) and here (whatwg).

After creating an instance of the TextEncoder it will take a string and encode it using a given encoding parameter:

if (!("TextEncoder" in window)) 
  alert("Sorry, this browser does not support TextEncoder...");

var enc = new TextEncoder(); // always utf-8
console.log(enc.encode("This is a a string to be converted to a Uint8Array"));
Run code snippetEdit code snippet Hide Results Copy to answer Expand

You then of course use the .buffer parameter on the resulting Uint8Array to convert the underlaying ArrayBuffer to a different view if needed.

Just make sure that the characters in the string adhere to the encoding schema, for example, if you use characters outside the UTF-8 range in the example they will be encoded to two bytes instead of one.

For general use you would use UTF-16 encoding for things like localStorage.

##TextDecoder

Likewise, the opposite process uses the TextDecoder:

The TextDecoder interface represents a decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, ... A decoder takes a stream of bytes as input and emits a stream of code points.

All available decoding types can be found here.

if (!("TextDecoder" in window))
  alert("Sorry, this browser does not support TextDecoder...");

var enc = new TextDecoder("utf-8");
var arr = new Uint8Array([84,104,105,115,32,105,115,32,97,32,85,105,110,116,
                          56,65,114,114,97,121,32,99,111,110,118,101,114,116,
                          101,100,32,116,111,32,97,32,115,116,114,105,110,103]);
console.log(enc.decode(arr));
Run code snippetEdit code snippet Hide Results Copy to answer Expand

##The MDN StringView library

An alternative to these is to use the StringView library (licensed as lgpl-3.0) which goal is:

  • to create a C-like interface for strings (i.e., an array of character codes — an ArrayBufferView in JavaScript) based upon the JavaScript ArrayBuffer interface
  • to create a highly extensible library that anyone can extend by adding methods to the object StringView.prototype
  • to create a collection of methods for such string-like objects (since now: stringViews) which work strictly on arrays of numbers rather than on creating new immutable JavaScript strings
  • to work with Unicode encodings other than JavaScript's default UTF-16 DOMStrings

giving much more flexibility. However, it would require us to link to or embed this library while TextEncoder/TextDecoder is being built-in in modern browsers.

#Support

As of July/2018:

TextEncoder (Experimental, On Standard Track)

 Chrome    | Edge      | Firefox   | IE        | Opera     | Safari
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |    19°    |     -     |     25    |     -

 Chrome/A  | Edge/mob  | Firefox/A | Opera/A   |Safari/iOS | Webview/A
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |    19°    |     ?     |     -     |     38

°) 18: Firefox 18 implemented an earlier and slightly different version
of the specification.

WEB WORKER SUPPORT:

Experimental, On Standard Track

 Chrome    | Edge      | Firefox   | IE        | Opera     | Safari
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |     20    |     -     |     25    |     -

 Chrome/A  | Edge/mob  | Firefox/A | Opera/A   |Safari/iOS | Webview/A
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |     20    |     ?     |     -     |     38

Data from MDN - `npm i -g mdncomp` by epistemex
Answer from user1693593 on Stack Overflow
Top answer
1 of 16
352

Update 2016 - five years on there are now new methods in the specs (see support below) to convert between strings and typed arrays using proper encoding.

##TextEncoder

The TextEncoder represents:

The TextEncoder interface represents an encoder for a specific method, that is a specific character encoding, liarraybufferke utf-8, iso-8859-2, koi8, cp1261, gbk, ... An encoder takes a stream of code points as input and emits a stream of bytes.

Change note since the above was written: (ibid.)

Note: Firefox, Chrome and Opera used to have support for encoding types other than utf-8 (such as utf-16, iso-8859-2, koi8, cp1261, and gbk). As of Firefox 48 [...], Chrome 54 [...] and Opera 41, no other encoding types are available other than utf-8, in order to match the spec.*

*) Updated specs (W3) and here (whatwg).

After creating an instance of the TextEncoder it will take a string and encode it using a given encoding parameter:

if (!("TextEncoder" in window)) 
  alert("Sorry, this browser does not support TextEncoder...");

var enc = new TextEncoder(); // always utf-8
console.log(enc.encode("This is a a string to be converted to a Uint8Array"));
Run code snippetEdit code snippet Hide Results Copy to answer Expand

You then of course use the .buffer parameter on the resulting Uint8Array to convert the underlaying ArrayBuffer to a different view if needed.

Just make sure that the characters in the string adhere to the encoding schema, for example, if you use characters outside the UTF-8 range in the example they will be encoded to two bytes instead of one.

For general use you would use UTF-16 encoding for things like localStorage.

##TextDecoder

Likewise, the opposite process uses the TextDecoder:

The TextDecoder interface represents a decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, ... A decoder takes a stream of bytes as input and emits a stream of code points.

All available decoding types can be found here.

if (!("TextDecoder" in window))
  alert("Sorry, this browser does not support TextDecoder...");

var enc = new TextDecoder("utf-8");
var arr = new Uint8Array([84,104,105,115,32,105,115,32,97,32,85,105,110,116,
                          56,65,114,114,97,121,32,99,111,110,118,101,114,116,
                          101,100,32,116,111,32,97,32,115,116,114,105,110,103]);
console.log(enc.decode(arr));
Run code snippetEdit code snippet Hide Results Copy to answer Expand

##The MDN StringView library

An alternative to these is to use the StringView library (licensed as lgpl-3.0) which goal is:

  • to create a C-like interface for strings (i.e., an array of character codes — an ArrayBufferView in JavaScript) based upon the JavaScript ArrayBuffer interface
  • to create a highly extensible library that anyone can extend by adding methods to the object StringView.prototype
  • to create a collection of methods for such string-like objects (since now: stringViews) which work strictly on arrays of numbers rather than on creating new immutable JavaScript strings
  • to work with Unicode encodings other than JavaScript's default UTF-16 DOMStrings

giving much more flexibility. However, it would require us to link to or embed this library while TextEncoder/TextDecoder is being built-in in modern browsers.

#Support

As of July/2018:

TextEncoder (Experimental, On Standard Track)

 Chrome    | Edge      | Firefox   | IE        | Opera     | Safari
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |    19°    |     -     |     25    |     -

 Chrome/A  | Edge/mob  | Firefox/A | Opera/A   |Safari/iOS | Webview/A
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |    19°    |     ?     |     -     |     38

°) 18: Firefox 18 implemented an earlier and slightly different version
of the specification.

WEB WORKER SUPPORT:

Experimental, On Standard Track

 Chrome    | Edge      | Firefox   | IE        | Opera     | Safari
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |     20    |     -     |     25    |     -

 Chrome/A  | Edge/mob  | Firefox/A | Opera/A   |Safari/iOS | Webview/A
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |     20    |     ?     |     -     |     38

Data from MDN - `npm i -g mdncomp` by epistemex
2 of 16
207

Although Dennis and gengkev solutions of using Blob/FileReader work, I wouldn't suggest taking that approach. It is an async approach to a simple problem, and it is much slower than a direct solution. I've made a post in html5rocks with a simpler and (much faster) solution: http://updates.html5rocks.com/2012/06/How-to-convert-ArrayBuffer-to-and-from-String

And the solution is:

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}

function str2ab(str) {
  var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
  var bufView = new Uint16Array(buf);
  for (var i=0, strLen=str.length; i<strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

EDIT:

The Encoding API helps solving the string conversion problem. Check out the response from Jeff Posnik on Html5Rocks.com to the above original article.

Excerpt:

The Encoding API makes it simple to translate between raw bytes and native JavaScript strings, regardless of which of the many standard encodings you need to work with.

<pre id="results"></pre>

<script>
  if ('TextDecoder' in window) {
    // The local files to be fetched, mapped to the encoding that they're using.
    var filesToEncoding = {
      'utf8.bin': 'utf-8',
      'utf16le.bin': 'utf-16le',
      'macintosh.bin': 'macintosh'
    };

    Object.keys(filesToEncoding).forEach(function(file) {
      fetchAndDecode(file, filesToEncoding[file]);
    });
  } else {
    document.querySelector('#results').textContent = 'Your browser does not support the Encoding API.'
  }

  // Use XHR to fetch `file` and interpret its contents as being encoded with `encoding`.
  function fetchAndDecode(file, encoding) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file);
    // Using 'arraybuffer' as the responseType ensures that the raw data is returned,
    // rather than letting XMLHttpRequest decode the data first.
    xhr.responseType = 'arraybuffer';
    xhr.onload = function() {
      if (this.status == 200) {
        // The decode() method takes a DataView as a parameter, which is a wrapper on top of the ArrayBuffer.
        var dataView = new DataView(this.response);
        // The TextDecoder interface is documented at http://encoding.spec.whatwg.org/#interface-textdecoder
        var decoder = new TextDecoder(encoding);
        var decodedString = decoder.decode(dataView);
        // Add the decoded file's text to the <pre> element on the page.
        document.querySelector('#results').textContent += decodedString + '\n';
      } else {
        console.error('Error while requesting', file, this);
      }
    };
    xhr.send();
  }
</script>
🌐
Reddit
reddit.com › r/learnprogramming › js: how to convert arraybuffer to string?
r/learnprogramming on Reddit: JS: How to convert ArrayBuffer to string?
May 2, 2023 -

Working with Web Push Notifications.

https://developer.mozilla.org/en-US/docs/Web/API/PushSubscription

I got the Push Subscription Object.

I get the keys for p256dh and auth, using PushSubscription.getKey()

Unfortunately, getKey() returns an ArrayBuffer per the docs.

I need to save this subscription object with JSON.stringify(), specifically because I am creating a new object and can't use the toJSON() method which is part of the original Push Subscription Object.

When converting to JSON , ArrayBuffer disappears. So I get an empty object.

Thus, I need to convert the ArrayBuffer to a string before sending to the server.

How do I do this? I saw the Buffer suggested, but thats only available on server side.

Discussions

arraybuffer - JavaScript- convert array buffer to string - Stack Overflow
Title says it all. I have a jquery serialized data that looks like this: tarid=value&tarname=value&sel=3 And I want to convert it to ArrayBuffer. After that, I also need to turn it back to... More on stackoverflow.com
🌐 stackoverflow.com
July 4, 2016
javascript - how to convert arraybuffer to string - Stack Overflow
I have written a simple TCP server on node.js to send some data to a Chrome app. In the chrome app, when I get the data, I convert that to string using below function, I get an exception "byte leng... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Converting array buffer in string - Stack Overflow
I am stuck in converting arraybuffer to string in typescript (angular 4 project). Any help is highly appreciated. Code output is showing string but with this sign - � Required Output : PROGRAM " More on stackoverflow.com
🌐 stackoverflow.com
November 22, 2017
JS: How to convert ArrayBuffer to string?
Convert it to a Uint8Array, then convert that to a base64 string with btoa: https://stackoverflow.com/questions/9267899/arraybuffer-to-base64-encoded-string More on reddit.com
🌐 r/learnprogramming
1
1
May 2, 2023
🌐
LearnersBucket
learnersbucket.com › home › examples › javascript › javascript program to convert array buffer to string
JavaScript program to convert array buffer to string - LearnersBucket
April 28, 2023 - First, we will convert the key buffer to unit8Array and then convert each byte to string using the fromCodePoint method of the string. const arrayBufferToString = (exportedPrivateKey) => { const byteArray = new Uint8Array(exportedPrivateKey); let byteString = ''; for(var i=0; i < ...
🌐
GitHub
gist.github.com › skratchdot › e095036fad80597f1c1a
Array Buffer -> String and String -> ArrayBuffer conversions in javascript · GitHub
Save skratchdot/e095036fad80597f1c1a to your computer and use it in GitHub Desktop. Download ZIP · Array Buffer -> String and String -> ArrayBuffer conversions in javascript · Raw · arrayBufferToString.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › ArrayBuffer
ArrayBuffer - JavaScript - MDN Web Docs
It is an array of bytes, often referred to in other languages as a "byte array". You cannot directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.
🌐
npm
npmjs.com › package › arraybuffer-to-string
arraybuffer-to-string - npm
Convert ArrayBuffer to string with optional encoding. ... Convert ArrayBuffer/ArrayBufferView/Array buffer to string with defined encoding.
      » npm install arraybuffer-to-string
    
Published: Feb 23, 2018
Version: 1.0.2
Top answer
1 of 1
15

is this enough?

function stringToArrayBuffer(str){
    if(/[\u0080-\uffff]/.test(str)){
        throw new Error("this needs encoding, like UTF-8");
    }
    var arr = new Uint8Array(str.length);
    for(var i=str.length; i--; )
        arr[i] = str.charCodeAt(i);
    return arr.buffer;
}

function arrayBufferToString(buffer){
    var arr = new Uint8Array(buffer);
    var str = String.fromCharCode.apply(String, arr);
    if(/[\u0080-\uffff]/.test(str)){
        throw new Error("this string seems to contain (still encoded) multibytes");
    }
    return str;
}

or do you need real UTF-8 encoding

Edit: full UTF-8 support

Beware/Disclaimer: this code is not tested against some foreign implementaion of an UTF-8 encoder or decoder. It may produce wrong results.

TEST IT YOURSELF, before you use it in production!

function stringToArrayBuffer(str){
    if(/[\u0080-\uffff]/.test(str)){
        var arr = new Array(str.length);
        for(var i=0, j=0, len=str.length; i<len; ++i){
            var cc = str.charCodeAt(i);
            if(cc < 128){
                //single byte
                arr[j++] = cc;
            }else{
                //UTF-8 multibyte
                if(cc < 2048){
                    arr[j++] = (cc >> 6) | 192;
                }else{
                    arr[j++] = (cc >> 12) | 224;
                    arr[j++] = ((cc >> 6) & 63) | 128;
                }
                arr[j++] = (cc & 63) | 128;
            }
        }
        var byteArray = new Uint8Array(arr);
    }else{
        var byteArray = new Uint8Array(str.length);
        for(var i = str.length; i--; )
            byteArray[i] = str.charCodeAt(i);
    }
    return byteArray.buffer;
}

function arrayBufferToString(buffer){
    var byteArray = new Uint8Array(buffer);
    var str = "", cc = 0, numBytes = 0;
    for(var i=0, len = byteArray.length; i<len; ++i){
        var v = byteArray[i];
        if(numBytes > 0){
            //2 bit determining that this is a tailing byte + 6 bit of payload
            if((cc&192) === 192){
                //processing tailing-bytes
                cc = (cc << 6) | (v & 63);
            }else{
                throw new Error("this is no tailing-byte");
            }
        }else if(v < 128){
            //single-byte
            numBytes = 1;
            cc = v;
        }else if(v < 192){
            //these are tailing-bytes
            throw new Error("invalid byte, this is a tailing-byte")
        }else if(v < 224){
            //3 bits of header + 5bits of payload
            numBytes = 2;
            cc = v & 31;
        }else if(v < 240){
            //4 bits of header + 4bit of payload
            numBytes = 3;
            cc = v & 15;
        }else{
            //UTF-8 theoretically supports up to 8 bytes containing up to 42bit of payload
            //but JS can only handle 16bit.
            throw new Error("invalid encoding, value out of range")
        }

        if(--numBytes === 0){
            str += String.fromCharCode(cc);
        }
    }
    if(numBytes){
        throw new Error("the bytes don't sum up");
    }
    return str;
}
Find elsewhere
🌐
LearnersBucket
learnersbucket.com › home › examples › javascript › javascript program to convert a string to array buffer
JavaScript program to convert a string to array buffer - LearnersBucket
April 28, 2023 - 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.
🌐
GeeksforGeeks
geeksforgeeks.org › node-js-npm-arraybuffer-to-string-module
Node.js NPM arraybuffer-to-string Module | GeeksforGeeks
January 11, 2022 - There is an NPM package called arraybuffer-to-string used to decode array buffers in actual strings. The package not only converts the buffer to 'utf8' string but also it converts the buffer to many forms like base64 encoded string, a hex-encoded ...
🌐
Adeva
adevait.com › nodejs › convert-node-js-buffer-to-string
How to Convert Node.js Buffer to String | Toptal®
May 26, 2026 - A Buffer object is a way to abstract sequences or arrays of bytes. Besides common array operations like getting and changing one or more elements of the byte array, Buffers usually have advanced methods to read and write more complex values such as integers, floating point numbers and strings.
🌐
W3Schools
w3schools.com › js › js_arraybuffers.asp
JavaScript Array Buffer
Converting an ArrayBuffer to a String (UTF-8) function arrayBufferToString(buffer) { const decoder = new TextDecoder(); return decoder.decode(new Uint8Array(buffer)); } const encoder = new TextEncoder(); const myBuf = encoder.encode("Hello ...
🌐
Webdevtutor
webdevtutor.net › blog › javascript-buffer-array-to-string
Converting a JavaScript Buffer Array to String: A Comprehensive Guide
Another approach involves using String.fromCharCode() to convert each byte in the Buffer array into a character and then joining them to form a string: javascript const buffer = Buffer.from([87, 111, 114, 108, 100]); const str = Array.from(buffer).map(byte => String.fromCharCode(byte)).join(''); ...
🌐
Jamie Tanna
jvt.me › posts › 2020 › 04 › 20 › buffer-array-to-string
Converting a Byte Array to String with `Buffer` in Node.JS · Jamie Tanna | Software Engineer
April 20, 2020 - But what happens when you have serialised it, and you want to convert it back to a String? ... const bytes = [ 104, 116, 116, 112, 115, 58, 47, 47, 119, 119, 119, 46, 106, 118, 116, 46, 109, 101 ]; console.log(new Buffer.from(bytes).toString()); // 'https://www.jvt.me' This post's permalink is https://www.jvt.me/posts/2020/04/20/buffer-array-to-string/ and has the following summary:.
Top answer
1 of 4
14

The modern (Chrome 38+) way to do this would be, assuming the encoding is UTF-8:

var decoder = new TextDecoder("utf-8");

function arrayBufferToString(buffer) {
    return decoder.decode(new Uint8Array(buffer));
}

This uses the TextDecoder API; see documentation for more options, such as a different encoding.

See also: Easier ArrayBuffer<->String conversion with the Encoding API @ Google Developers

2 of 4
9

You're probably seeing this problem because your app has received an odd number of bytes on the socket, but you're trying to create an array of 2-byte-wide items out of it (because that's what fits into a Uint16Array)

If your app receives the string "Hello" over the network (5 bytes), then you can cast that to a Uint8Array, and it will look like this:

Item:        0   1   2   3   4
Char:        H   e   l   l   o
Uint8 Value: 72  101 108 108 111

casting it to an Uint16Array, though will try to do this:

Item   0     1     2
Chars  He    ll    o?
IntVal 25928 27756 ?????

Without a 6th byte to work with, it can't construct the array, and so you get an exception.

Using a Uint16Array for the data only makes sense if you are expecting UCS-2 string data on the socket. If you are receiving plain ASCII data, then you want to cast that to a Uint8Array instead, and map String.fromCharCode on that. If it's something else, such as UTF-8, then you'll have to do some other conversion.

No matter what, though, the socket layer is always free to send you data in chunks of any length. Your app will have to deal with odd sizes, and save any remainder that you can't deal with right away, so that you can use it when you receive the next chunk of data.

🌐
GitHub
github.com › dy › arraybuffer-to-string
GitHub - dy/arraybuffer-to-string: Convert ArrayBuffer to string · GitHub
var ab2str = require('arraybuffer-to-string') var uint8 = new Uint8Array([ 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 ]) ab2str(uint8) // 'Hello World!' ab2str(uint8, 'base64') // 'SGVsbG8gV29ybGQh' ab2str(uint8, 'hex') // '48656c6c6f20576f726c6421' ab2str(uint8, 'iso-8859-2') // 'Hello World!' Convert ArrayBuffer/ArrayBufferView/Array buffer to string with defined encoding.
Author: dy
🌐
Bun
bun.com › convert an arraybuffer to a string
Convert an ArrayBuffer to a string - Bun
August 7, 2026 - Bun implements the Web-standard TextDecoder class for converting between binary data types and strings. const buf = new ArrayBuffer(64); const decoder = new TextDecoder(); const str = decoder.decode(buf);
🌐
Telerik
telerik.com › blogs › array-buffers-javascript
Array Buffers in JavaScript
October 22, 2025 - In the code above, we are reading the code of different data types stored in the buffer and getting them according to their offset. JavaScript provides several methods to convert between strings and ArrayBuffers, which is essential for tasks such as encoding, decoding and managing data streams.
🌐
Chrome Developers
developer.chrome.com › blog › how to convert arraybuffer to and from string
How to convert ArrayBuffer to and from String | Blog | Chrome for Developers
June 14, 2012 - See Easier ArrayBuffer <-> String conversion with the Encoding API for more details. ArrayBuffers are used to transport raw data and several new APIs rely on them, including WebSockets, Web Intents 2](https://www.html5rocks.com/en/tutorials/file/xhr2/) and WebWorkers. However, because they recently landed in the JavaScript world, sometimes they are misinterpreted or misused.