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
🌐
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) Copy link ·
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>
Discussions

Converting array buffer in string - javascript
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
how to convert arraybuffer to string - javascript
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
html - can i convert ArrayBuffer to string? - Stack Overflow
I am working on html5 uploading script. I want md5 hash for every chunk of file stream. here is I am using FileReader for reading stream but when I pass reader result to base64 class I got excepti... More on stackoverflow.com
🌐 stackoverflow.com
How do I add Blob to typescript?

I believe you just need to add "dom" in your lib tsconfig.json

"lib": \[  
 "esnext",  
 "dom",  
 "dom.iterable",  
 "scripthost"  
\]

Or you can copy paste the definition from there"

https://github.com/microsoft/TypeScript/blob/master/lib/lib.dom.d.ts

/** A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. */
interface Blob {
    readonly size: number;
    readonly type: string;
    slice(start?: number, end?: number, contentType?: string): Blob;
}

declare var Blob: {
    prototype: Blob;
    new(blobParts?: BlobPart[], options?: BlobPropertyBag): Blob;
};


interface BlobPropertyBag {
    endings?: EndingType;
    type?: string;
}

type EndingType = "transparent" | "native";

type BlobPart = BufferSource | Blob | string;

type BufferSource = ArrayBufferView | ArrayBuffer;

...
More on reddit.com
🌐 r/typescript
20
1
July 3, 2019
🌐
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.

🌐
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);
🌐
Webdevtutor
webdevtutor.net › blog › typescript-array-buffer-to-string
Converting ArrayBuffer to String in TypeScript: A Comprehensive Guide
One of the most common ways to convert an ArrayBuffer to a string in TypeScript is by using the TextDecoder API.
🌐
Webdevtutor
webdevtutor.net › blog › typescript-arraybuffer-to-string
Converting ArrayBuffer to String in TypeScript
If you prefer a manual approach, you can iterate over the elements of the ArrayBuffer and construct the string character by character.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › ArrayBuffer
ArrayBuffer - JavaScript - MDN Web Docs
You cannot directly manipulate ... 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 ...
🌐
npm
npmjs.com › package › arraybuffer-to-string
arraybuffer-to-string - npm
Convert ArrayBuffer/ArrayBufferView/Array buffer to string with defined encoding.
      » npm install arraybuffer-to-string
    
Published: Feb 23, 2018
Version: 1.0.2
Find elsewhere
🌐
Bun
bun.com › 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);
🌐
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!'
Author: dy
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.

🌐
DEV Community
dev.to › masanori_msl › typescript-convert-from-typescriptjavascript-data-type-to-binary-data-372
[TypeScript] Convert from TypeScript(JavaScript) data type to binary data - DEV Community
November 7, 2021 - TypeScript 4.4.4 · I can convert string values by "TextDecoder" and "TextEncoder". export function init(): void { const originalText = "こんにちは"; const textBuffer = convertFromStringToBuffer(originalText); console.log(textBuffer); const convertedText = convertFromBufferToString(textBuffer); console.log(convertedText); } function convertFromStringToBuffer(value: string): ArrayBuffer { // Encode with UTF-8 const encoder = new TextEncoder(); return encoder.encode(value); } function convertFromBufferToString(value: ArrayBuffer): string { // Decode with UTF-8 const decoder = new TextDecoder(); return decoder.decode(value); } Uint8Array(15) [227, 129, 147, 227, 130, 147, 227, 129, 171, 227, 129, 161, 227, 129, 175, buffer: ArrayBuffer(15), byteLength: 15, byteOffset: 0, length: 15] こんにちは ·
🌐
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 < ...
🌐
JSFiddle
jsfiddle.net › fuck_off_u_bastard › string to arraybuffer & vice-versa
String To ArrayBuffer & Vice-Versa - JSFiddle - React, Tailwind, and code Playground
December 7, 2016 - 4 bytes JSON => JSON.stringify({data: 'Hello World!'}); */ var string = 'Hello World!'; var buffer = new ArrayBuffer(string.length*2); var bufferView = new Uint16Array(buffer); for (var i = 0; i < string.length; i++) { bufferView[i] = string.charCodeAt(i); } console.log(bufferView); /* # ArrayBuffer to String Conversion # alternative to 'bufferView' => new Uint16Array(buffer) JSON => JSON.parse(_string).data */ var _string = String.fromCharCode.apply(null, bufferView); console.log(_string); /* As individual functions function str2arr(str, callback) { var array = new ArrayBuffer(str.length); var bufferView = new Uint8Array(array); for (var i = 0; i < str.length; i++) { bufferView[i] = str.charCodeAt(i); } callback(bufferView); } function arr2str(arr, callback) { var _arr = String.fromCharCode.apply(null, arr); callback(_arr); } */
Published: Dec 07, 2016
Author: fuck_off_u_bastard
🌐
Tricentis
tabnine.com › home › products overview
Agentic Quality Engineering Platform - Tricentis
January 31, 2018 - Describe what you want tested and the agent navigates the application, maps the fields, builds the test, and debugs itself when it breaks. Teams report up to 60% productivity gains, and non-experts can finally contribute to automation.
🌐
Adeva
adevait.com › nodejs › convert-node-js-buffer-to-string
How to Convert Node.js Buffer to String | Toptal®
May 26, 2026 - In a nutshell, it’s easy to convert a Buffer object to a string using the toString() method. You’ll usually want the default UTF-8 encoding, but it’s possible to indicate a different encoding if needed.
🌐
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) ...ePointAt(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 - NPM(Node Package Manager) is a package manager of Node.js packages. There is an NPM package called arraybuffer-to-string used to decode array buffers in actual strings.