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
🌐
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.
🌐
DEV Community
dev.to › melvin2016 › how-to-convert-a-string-to-buffer-and-vice-versa-in-node-js-5op
How to convert a String to Buffer and vice versa in Node.js - DEV Community
September 19, 2020 - To convert a string to a Buffer, you can use the from() method from the global Buffer class in Node.js.
Discussions

javascript - Converting between strings and ArrayBuffers
I'm not an expert but an example in the browser is the USVString you can receive from a blob. developer.mozilla.org/en-US/docs/Web/API/Blob/text 2021-09-22T22:54:21.853Z+00:00 ... If you're starting from a blob you probably shouldn't convert it to a string to then make a buffer, since ... More on stackoverflow.com
🌐 stackoverflow.com
node.js - Convert string to buffer Node - Stack Overflow
I am using a library which on call of a function returns the toString of a buffer. ... But I don't want string version of it. More on stackoverflow.com
🌐 stackoverflow.com
Browser buffer to string conversion is not same in browser and nodejs
I have encountered an interesting issue. I'm using node v8.1.4 I have the following buffer. [ 191, 164, 235, 131, 30, 28, 164, 179, 101, 138, 94, 36, 115, 176, 83, 193, 9, 177, 85, 228, 189, 1... More on stackoverflow.com
🌐 stackoverflow.com
Convert String to base64
Buffer.from creates a buffer (aka raw binary data), not an encoded string, the argument that you provide is the encoding the string is currently in. In order to change the encoding, you have to encode it again: Buffer.from("some string", "utf8").toString("base64") Similar to reverse the process: Buffer.from("c29tZSBzdHJpbmc=", "base64").toString("utf8") More on reddit.com
🌐 r/learnjavascript
5
5
March 6, 2023
🌐
W3Schools
w3schools.com › nodejs › met_buffer_tostring.asp
Node.js buffer toString() Method
The toString() method returns the buffer object according to the specified encoding.
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>
🌐
Melvin George
melvingeorge.me › blog › convert-string-buffer-nodejs
How to convert a String to Buffer and vice versa in Node.js | MELVIN GEORGE
September 19, 2020 - To convert a string to a Buffer, you can use the from() method from the global Buffer class in Node.js.
🌐
Futurestud.io
futurestud.io › tutorials › node-js-convert-a-string-to-buffer
Node.js — Convert a String to Buffer - Future Studio
June 22, 2023 - The second argument to Buffer.from(input, encoding) is the encoding of your input value. In case you’re working with a different encoding than UTF-8, you can provide it there. Node.js supports a variety of encoding, like ascii, hex, base64, and so on. If you want to make sure you’re properly using string inputs to create your buffers, you may build yourself a small utility function that checks the type of the input parameter:
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › ArrayBuffer
ArrayBuffer - JavaScript - MDN Web Docs
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.
🌐
GitHub
github.com › raypulver › string-buffer
GitHub - raypulver/string-buffer: An implementation of the Node.js Buffer to be used in the browser. · GitHub
This is the StringBuffer class that LEON uses internally. It provides all the methods of a Node.js Buffer object, but it stores its data in a string, meaning it is portable enough to be used in the browser as well as on the server.
Author: raypulver
🌐
Node.js
nodejs.org › api › buffer.html
Buffer | Node.js v26.10.0 Documentation
Node.js also supports the following binary-to-text encodings. For binary-to-text encodings, the naming convention is reversed: Converting a Buffer into a string is typically referred to as encoding, and converting a string into a Buffer as decoding.
🌐
GitHub
gist.github.com › kawanet › 352a2ed1d1656816b2bc
String と ArrayBuffer の相互変換 JavaScript · GitHub
string_to_buffer.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. Learn more about bidirectional Unicode characters ·
🌐
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.
🌐
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 - A buffer is created from a string using Buffer.from. The buffer is then converted back to a string using the toString method.
🌐
W3Schools
w3schools.com › nodejs › met_buffer_from.asp
Node.js Buffer.from() Method
The Buffer.from() method creates a new buffer filled with the specified string, array, or buffer. ... Coding fundamentals as bite-sized lessons and challenges. ... If you want to use W3Schools services as an educational institution, team or ...
🌐
Scaler
scaler.com › home › topics › nodejs › buffers and string decoders in node.js
Buffers and String Decoders in Node.js - Scaler Topics
May 4, 2023 - It is accessible in the application without the need to import the buffer module. ... A Node buffer can be built in a variety of ways. The three most common ways are as follows : Create an uninitiated buffer: Following is the syntax of creating a buffer of 15 octets without any initialization. Create a buffer from the array: The syntax for creating a Buffer from an array is as follows. Create a buffer from string: The syntax for creating a Buffer from a given string and optionally encoding type is as follows.
🌐
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 › javascript › convert-base64-string-to-arraybuffer-in-javascript
Convert base64 String to ArrayBuffer In JavaScript - GeeksforGeeks
August 5, 2025 - Example: This function converts a Base64-encoded string into an ArrayBuffer using the TextEncoder to encode the binary string. ... function base64ToArrayBuffer(base64) { const binaryString = atob(base64); const encoder = new TextEncoder(); const binaryArray = encoder.encode(binaryString); return binaryArray.buffer; } const base64String = "SGVsbG8gd29ybGQ="; const arrayBuffer = base64ToArrayBuffer(base64String); console.log(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 - Note: A robust implementation of the String to ArrayBuffer conversion capable of handling more encodings is provided by the stringencoding library. But, for simple usage where you control both sides of the communication pipe, the code above is probably enough.