You can use Buffer.from(string[, encoding]). The Buffer class has implemented the Uint8Array interface in Node since v4.x. You can also optionally specify an encoding with which to do string processing in both directions, i.e. buffer.toString([encoding]).

Answer from Patrick Roberts on Stack Overflow
🌐
haikel-fazzani
haikel-fazzani.eu.org › home › javascript snippets › convert a string to uint8array in javascript (and back)
Convert a String to Uint8Array in JavaScript (and Back)
October 23, 2024 - Use new TextEncoder().encode(text) to convert a JavaScript string to a UTF-8 Uint8Array. Convert it back with new TextDecoder().decode(bytes). These APIs are Unicode-safe and work in modern browsers and Node.js.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Uint8Array › fromHex
Uint8Array.fromHex() - JavaScript - MDN Web Docs
July 10, 2025 - The Uint8Array.fromHex() static method creates a new Uint8Array object from a hexadecimal string. This method parses the string into a byte array. To convert the string into a single number, use the parseInt() function with radix set to 16 instead.
🌐
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_textStr_to_utf8Array_way0(text_str) { // Way 0 // Encode the text string into a TypedArray of [non-fixed length]. const uint8Array_nonfixedLength_way0 = new TextEncoder().encode(text_str); console.log('uint8Array_nonfixedLength_way0:', uint8Array_nonfixedLength_way0); return uint8Array_nonfixedLength_way0; }
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › TextEncoder › encodeInto
TextEncoder: encodeInto() method - Web APIs | MDN
June 28, 2025 - The TextEncoder.encodeInto() method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns an object indicating the progress of the encoding. This is potentially more performant than the encode() method — especially when the target buffer ...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript-uint8array-from-method
JavaScript Uint8Array.from() Method | GeeksforGeeks
January 9, 2024 - The Uint8Array.from() method in JavaScript is used to create a new Uint8Array from an array-like or iterable object.
Find elsewhere
🌐
Coolaj86
coolaj86.com › articles › unicode-string-to-a-utf-8-typed-array-buffer-in-javascript
Unicode String to a UTF-8 TypedArray Buffer in JavaScript
June 26, 2015 - This is truly "vanilla" JavaScript that can easily be adapted to work even in weird environments (such as Windows Scripting Host, TI's ARM build system, Rhino, node.js, MSIE6). Note: Working in weird environments is not a design goal of this code. Hence, I don't do anything "wonky" to acheive that. To run this in MSIE6 you would simply need to replace Uint8Array() with Array() and provide a a polyfill for 'map' and 'forEach'. 'use strict'; // string to uint array function unicodeStringToTypedArray(s) { var escstr = encodeURIComponent(s); var binstr = escstr.replace(/%([0-9A-F]{2})/g, function(match, p1) { return String.fromCharCode('0x' + p1); }); var ua = new Uint8Array(binstr.length); Array.prototype.forEach.call(binstr, function (ch, i) { ua[i] = ch.charCodeAt(0); }); return ua; } Demo ·
🌐
GitHub
gist.github.com › skratchdot › e095036fad80597f1c1a
Array Buffer -> String and String -> ArrayBuffer conversions in javascript · GitHub
const byteArrayString = String.fromCharCode.apply(null, Array.from(new Uint8Array(anArrayBufferC))); The above code giving me "Maximum call stack size exceeded" error. Please help ... @erycson - nice! It looks like TextEncoder/TextDecoder is now a global in node (as of v11.0.0). It was added in the util lib in v8.3.0. Following your example. the ab2str function can be rewritten: function ab2str(buf) { return new TextDecoder().decode(buf); } ... Very good! Had to change the Uint16Array to Uint8Array and worked like a charm!
🌐
Gnipbao's blog
gnipbao.github.io › 2017 › 11 › 15 › Uint8Array-to-string
Uint8Array to string in Javascript - Gnipbao's blog
December 16, 2017 - Little strings少量数据使用超出异常123456789/** * little arrays (>=100k characters), otherwise you'll get exceptions as RangeError : Maximum call * stack size exceeded or Out of stack space. * @returns &#12
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › TypedArray › toString
TypedArray.prototype.toString() - JavaScript - MDN Web Docs
July 10, 2025 - See Array.prototype.toString() for more details. This method is not generic and can only be called on typed array instances. ... const uint8 = new Uint8Array([1, 2, 3]); // Explicit conversion console.log(uint8.toString()); // 1,2,3 // Implicit conversion console.log(`${uint8}`); // 1,2,3
🌐
npm
npmjs.com › package › uint8arrays
uint8arrays - npm
May 7, 2026 - Returns a new Uint8Array created from the passed string and interpreted as the passed encoding.
      » npm install uint8arrays
    
Published: May 07, 2026
Version: 6.1.1
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>
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Uint8Array › fromBase64
Uint8Array.fromBase64() - JavaScript - MDN Web Docs
The Uint8Array.fromBase64() static method creates a new Uint8Array object from a base64-encoded string. This method should be preferred over Window.atob() because it results in a byte array, which is easier to work with than a string containing raw bytes, unless your decoded binary data is ...
🌐
Our Code World
ourcodeworld.com › articles › read › 164 › how-to-convert-an-uint8array-to-string-in-javascript
How to convert an Uint8Array to string in Javascript | Our Code World
June 7, 2016 - * * @returns {String} */ function Decodeuint8arr(uint8array){ return new TextDecoder("utf-8").decode(uint8array); } /** * Convert a string into a Uint8Array. * * @returns {Uint8Array} */ function Encodeuint8arr(myString){ return new TextEncoder("utf-8").encode(myString); } The following method is very useful and works pretty good. It doesn't use any hacks nor depends on Browser JS functions, e.g.