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"));

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

##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"));

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

##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>
🌐
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.
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
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
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
Base64 to ArrayBuffer conversion is generating corrupted image file
This post helped me solving the problem. const imageBase64Str = req.body.logo.replace(/^.+,/, '') const buf = Buffer.from(imageBase64Str, 'base64') More on reddit.com
🌐 r/node
4
0
February 12, 2023
🌐
JSFiddle
jsfiddle.net › pundoo › w6dyv19f
String To ArrayBuffer & Vice-Versa - JSFiddle - Code Playground
JSFiddle - Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle.
🌐
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 - To convert the string, we will first create a unit8Array of the strings length size and then using the codePointAt method of string, get the Unicode of each character. const stringToArrayBuffer = (string) => { let byteArray = new Uint8Array(string.length); for(var i=0; i < string.length; i++) ...
🌐
GitHub
gist.github.com › amsul › 101a9c1c00597ab96e0b23cf649d50cb
Convert a string to an array buffer with JavaScript · GitHub
Convert a string to an array buffer with JavaScript · Raw · stringToBuffer.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
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) ... I just posted a TS conversion of this: https://gist.github.com/AndrewLeedham/a7f41ac6bb678f1eb21baf523aa71fd5 feel free to use it. I used Array.from to convert the Uint16Array to a number[]. Casting will also work if you don't want the extra operation.
🌐
npm
npmjs.com › package › string-to-arraybuffer
string-to-arraybuffer - npm
Latest version: 1.0.2, last published: 8 years ago. Start using string-to-arraybuffer in your project by running `npm i string-to-arraybuffer`. There are 21 other projects in the npm registry using string-to-arraybuffer.
      » npm install string-to-arraybuffer
    
Published   Nov 09, 2018
Version   1.0.2
🌐
GeeksforGeeks
geeksforgeeks.org › node.js › node-js-npm-string-to-arraybuffer-module
Node.js NPM string-to-arraybuffer Module - GeeksforGeeks
February 2, 2022 - Filename - index.js : This file contains logic to convert string to array buffer. ... const express = require('express') const bodyParser = require('body-parser') const str2Ab =require('string-to-arraybuffer') const formTemplet = require('./form') const app = express() const port = process.env.PORT || 3000 // The body-parser middleware to parse form data app.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML form app.get('/', (req, res) => { res.send(formTemplet({})) }) // Post route to handle form submission logic and app.post('/', (req, res) => { const {str} = req.bod
Find elsewhere
🌐
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
The conversion method depends on ... represents text (e.g., a JSON payload encoded in UTF-8), use the TextEncoder API to convert a JavaScript string to an ArrayBuffer....
🌐
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. Example: This function converts a Base64-encoded string into an ArrayBuffer.
🌐
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.
🌐
JavaScript in Plain English
javascript.plainenglish.io › how-to-convert-string-to-buffer-and-data-url-formats-using-client-side-javascript-9514a8c446d2
How To Convert String To Buffer And Data URL Formats Using Client-Side JavaScript | by Charmaine Chui | JavaScript in Plain English
May 30, 2025 - const str = 'Hey. this is a string!'; const buffer = Buffer.from(str, 'utf-8'); // format: ArrayBuffer const b64Str = Buffer.from(str, 'utf-8').toString('base64'); console.log(b64Str); /* Expected result: */ // SGV5LiB0aGlzIGlzIGEgc3RyaW5nIQ== const originalStr = Buffer.from(b64Str, 'base64').toString('utf-8'); console.log(originalStr); /* Expected result: */ // Hey. this is a string! ... New JavaScript and Web Development content every day.
🌐
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 ...
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;
}
🌐
Medium
medium.com › @j622amilah › javascript-basics-6-4b681b792298
JavaScript Basics 6. A list of conversion methods for… | by Practicing DatScy | Medium
November 22, 2024 - async function convert_utf8Array_to_arrayBuffer(uint8Array) { // Convert UTF-8 array [non-fixed length array] to a binary arrayBuffer [fixed-length array] const arrayBuffer = uint8Array_nonfixedLength.buffer; console.log("arrayBuffer:", ...
🌐
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.
🌐
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.

🌐
npm
npmjs.com › package › string-arraybuffer
string-arraybuffer - npm
March 25, 2018 - Easily convert string to arrayBuffer and from arrayBuffer to string · Useful when dealling with a function which accepts arraybuffer or return arraybuffer. $ npm install string-arraybuffer · const string_arraybuffer = require('string-arraybuffer'); ####Converting String to ArrayBuffer ·
      » npm install string-arraybuffer
    
Published   Mar 25, 2018
Version   1.0.4
Author   Andrews Agyemang Opoku
🌐
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