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>
🌐
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);
Discussions

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
nk.base64Decode() returns an ArrayBuffer, not a string in typescript - Heroic Labs Forum
In the nk.base64Decode() function description, the document says it returns an ArrayBuffer, but the example code returns a string. I think it’s better to return a string if possible. I’m having a hard time converting ArrayBuffer to string. Many of the methods recommended by Stack Overflow ... More on forum.heroiclabs.com
🌐 forum.heroiclabs.com
0
April 6, 2024
Efficient storage of ArrayBuffer / Uint8Array
I’m building new extension that will utilize Crypto API which returns ArrayBuffer, plus you need to store initialization vector which is Uint8Array. I will be storing these in the browser.storage.sync area which has only 100KB of space so I want to use it wisely - not wasting space. More on discourse.mozilla.org
🌐 discourse.mozilla.org
8
0
May 10, 2020
Best way of working with ArrayBuffers?
The standardised way is TextEncoder/Decoder , but it's relatively new. No IE or Safari support, but I imagine you can get properly vetted and supported polyfils (eg, https://github.com/inexorabletash/text-encoding , linked on the MDN page ). More on reddit.com
🌐 r/learnjavascript
5
2
June 30, 2016
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › ArrayBuffer
ArrayBuffer - JavaScript | MDN
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. The ArrayBuffer() constructor creates a new ArrayBuffer of the given length in bytes. You can also get an array buffer from existing data, for example, from a Base64 string or from a local file.
🌐
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.

🌐
Telerik
telerik.com › blogs › array-buffers-javascript
Array Buffers in JavaScript
October 22, 2025 - In the code above, input[type="file"] is an HTML tag for uploading a file. The file is read as an array buffer and later converted to a string to be displayed in the console.
🌐
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.
🌐
GitHub
gist.github.com › skratchdot › e095036fad80597f1c1a
Array Buffer -> String and String -> ArrayBuffer conversions in javascript · GitHub
What 's the cost of instantiating another ArrayBufferView ? is it minimal right ? I my case I work both with binary and text files and I read both using Uint8Array and this method works fine just passing it directly and in TypeScript I must cast to any: const s = String.fromCharCode.apply(null, anArrayBufferView as any)
Find elsewhere
🌐
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 ...
🌐
Toptal
toptal.com › external-blogs › adeva › 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.
🌐
Heroic Labs
forum.heroiclabs.com › runtime framework
nk.base64Decode() returns an ArrayBuffer, not a string in typescript - Heroic Labs Forum
April 6, 2024 - In the nk.base64Decode() function description, the document says it returns an ArrayBuffer, but the example code returns a string. I think it’s better to return a string if possible. I’m having a hard time converting ArrayBuffer to string. Many of the methods recommended by Stack Overflow cause errors.
🌐
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
🌐
Medium
medium.com › @ryan_forrester_ › buffer-to-string-in-javascript-how-to-guide-b24027575419
Buffer to String in JavaScript (How To Guide) | by ryan | Medium
January 7, 2025 - Converting a buffer to a string is a common requirement when dealing with data processing in JavaScript.
🌐
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:.
🌐
Node.js
nodejs.org › api › buffer.html
Buffer | Node.js v26.10.0 Documentation
javascriptcopy · A TypeError will be thrown if size is not a number. Added in: v0.1.90 · History · string <string> | <Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <SharedArrayBuffer> A value to calculate the length of. encoding <string> If string is a string, this is its encoding.
🌐
Mozilla Discourse
discourse.mozilla.org › add-ons › development
Efficient storage of ArrayBuffer / Uint8Array - Development - Mozilla Discourse
May 10, 2020 - I’m building new extension that will utilize Crypto API which returns ArrayBuffer, plus you need to store initialization vector which is Uint8Array. I will be storing these in the browser.storage.sync area which has onl…
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-convert-byte-array-to-string-in-javascript
JavaScript - Convert Byte Array to String - GeeksforGeeks
July 23, 2025 - JavaScript · const byteA = ... · Buffer.from() converts the byte array into a Node.js Buffer. The toString() method decodes the buffer into a string. This method uses String.fromCharCode to convert each byte in the array ...
🌐
Bun
bun.sh › guides › binary data › arraybuffer to string
Convert an ArrayBuffer to a string | Bun Guides
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);
🌐
Jsben
jsben.ch › convert-arraybuffer-to-base64-string-yduu9
Convert ArrayBuffer to Base64 string - JSBEN.CH JavaScript Benchmark
binary += String.fromCharCode(bytes[i]) } return btoa(binary) } arrayBufferToBase64(buffer) Pushing to a string array · 99 · 1 · 2 · 3 · 4 · 5 · 6 · 7 · 8 · 9 · 10 · 11 · 12 · 13 · › · ⌄ · ⌄ · function arrayBufferToBase64(buffer) { const binary = [] const bytes = new Uint8Array(buffer) const len = bytes.byteLength ·
🌐
Reddit
reddit.com › r/learnjavascript › string or buffer or arraybuffer?
r/learnjavascript on Reddit: string or Buffer or ArrayBuffer?
February 18, 2019 - Questions and posts about frontend development in general are welcome, as are all posts pertaining to JavaScript on the backend. ... I'm stuck with dealing with the issue of data types when dealing with IO. I want my code to be portable between node and the browser so that all IO code could work with Streams, Buffers or Blobs, File or ArrayBuffer. Blobs and Files are only really in the Browser. The main issue I have is that some functions return string and some ArrayBuffer