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>
      » npm install string-to-arraybuffer
    
Published: Nov 09, 2018
Version: 1.0.2
Discussions

ArrayBuffer to String, String to ArrayBuffer Method(s)
This question has received answers in the past, but I would definitely say that it is still not answered. There is almost documentation on ArrayBuffers in general, let alone on specific applicatio... More on stackoverflow.com
🌐 stackoverflow.com
Convert ArrayBuffer to Base64
this one looks badass https://www.npmjs.com/package/react-native-quick-base64 More on reddit.com
🌐 r/reactnative
8
3
April 17, 2024
How to return a large ArrayBuffer from a webassembly module?
WebAssembly memories can grow after they have initially been created, and the module's memory will do so when you allocate on the Rust side. This means you can allocate a large buffer on the Rust side. However there is no way to shrink a wasm linear memory as far as I know. Some possible approaches: Allocate one big buffer on the Rust side, and return a pointer + length to JS. JS reads the memory directly. Generate the result in chunks on the Rust side, and use a typed array (eg. Int32Array) to copy chunks of the data into an ArrayBuffer that is separate from the wasm memory. This can be done via the js_sys crate from Rust (see https://docs.rs/js-sys/latest/js_sys/struct.Int32Array.html#method.copy_from ) or via helper code written in JS More on reddit.com
🌐 r/rust
4
7
October 22, 2023
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
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › convert-base64-string-to-arraybuffer-in-javascript
Convert base64 String to ArrayBuffer In JavaScript - GeeksforGeeks
August 5, 2025 - The atob() function decodes a Base64-encoded string into a binary string. The Uint8Array constructor can then be used to convert this binary string into an ArrayBuffer.
🌐
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 - 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.
🌐
GitHub
github.com › dy › string-to-arraybuffer
GitHub - dy/string-to-arraybuffer: Convert plain/base64/datauri string to ArrayBuffer · GitHub
Turn dataURI/base64/plain string into an ArrayBuffer. var str2ab = require('string-to-arraybuffer') // Plain 'Hello World!' var abuf1 = str2ab('Hello World!') // Base-64 'Hello World!' var abuf2 = str2ab('SGVsbG8sIFdvcmxkIQ==') // Barebones data-uri 'Hello World!' var abuf3 = str2ab('data:,Hello, World!') // Base-64 data-uri 'Hello World!' var abuf4 = str2ab('data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==')
Author: dy
🌐
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
🌐
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 ...
🌐
Telerik
telerik.com › blogs › array-buffers-javascript
Array Buffers in JavaScript
October 22, 2025 - We can’t talk about conversion between strings and ArrayBuffer without talking about TextEncoder and TextDecoder. To convert a string to an ArrayBuffer, you typically need to encode the string into a binary format.
Find elsewhere
🌐
npm
npmjs.com › package › arraybuffer-to-string
arraybuffer-to-string - npm
string-to-arraybuffer − convert string to arraybuffer.
      » npm install arraybuffer-to-string
    
Published: Feb 23, 2018
Version: 1.0.2
🌐
GitHub
gist.github.com › don › 871170d88cf6b9007f7663fdbc23fe09
Convert hex string to ArrayBuffer · GitHub
Convert hex string to ArrayBuffer. GitHub Gist: instantly share code, notes, and snippets.
🌐
GitHub
gist.github.com › skratchdot › e095036fad80597f1c1a
Array Buffer -> String and String -> ArrayBuffer conversions in javascript · GitHub
Array Buffer -> String and String -> ArrayBuffer conversions in javascript - arrayBufferToString.js
🌐
npm
npmjs.com › package › string-arraybuffer
string-arraybuffer - npm
March 25, 2018 - A npm module for easy conversion from string to arraybuffer and from arraybuffer to string.. Latest version: 1.0.4, last published: 8 years ago. Start using string-arraybuffer in your project by running `npm i string-arraybuffer`. There are 2 other projects in the npm registry using string-arraybuffer.
      » npm install string-arraybuffer
    
Published: Mar 25, 2018
Version: 1.0.4
Author: Andrews Agyemang Opoku
🌐
GitHub
github.com › LinusU › array-buffer-from-string
GitHub - LinusU/array-buffer-from-string: Create an ArrayBuffer with the raw bytes from a String · GitHub
Create an ArrayBuffer with the raw bytes from a String. hex-to-array-buffer - Turn a string of hexadecimal characters into an ArrayBuffer
Author: LinusU
🌐
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 a NPM package called 'shortid' used to short non-sequential url-friendly unique ids. Command to install:Â Â npm install string-to-arraybuffer Syntax to import the package in local file const str2ab = require('string-to-array
🌐
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 - Here for testing, we are using the inverse method, string to array buffer. This will give us the array buffer of the given string and our method will turn that array buffer back to string. console.log(arrayBufferToString(stringToArrayBuffer("abcd"))); // "abcd"
🌐
GitHub
gist.github.com › kawanet › 352a2ed1d1656816b2bc
String と ArrayBuffer の相互変換 JavaScript · GitHub
Save kawanet/352a2ed1d1656816b2bc to your computer and use it in GitHub Desktop. Download ZIP · String と ArrayBuffer の相互変換 JavaScript · Raw · string_to_buffer.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
xjavascript
xjavascript.com › blog › converting-between-strings-and-arraybuffers
How to Efficiently Convert Strings to ArrayBuffers and Vice Versa in JavaScript: A Guide for localStorage Usage — xjavascript.com
LocalStorage is a popular client-side storage solution in JavaScript, ideal for persisting small to medium-sized data across browser sessions. However, it has a critical limitation: **it only stores string key-value pairs**. This becomes a problem when working with binary data, such as images, audio snippets, or serialized binary structures, which are often represented as `ArrayBuffer` objects in JavaScript.