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
🌐
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; }
🌐
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_way1(text_str) { // Way 1 // Transform text_str into Typed array. var character_array = text_str.split(''); console.log("character_array: ", character_array); // Array(38190) [ "�", "�", "�", ...
🌐
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.
🌐
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 ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › TextEncoder › encodeInto
TextEncoder: encodeInto() method - Web APIs | MDN
June 28, 2025 - const encoder = new TextEncoder(); function encodeIntoAtPosition(string, u8array, position) { return encoder.encodeInto( string, position ? u8array.subarray(position | 0) : u8array, ); } const u8array = new Uint8Array(8); encodeIntoAtPosition("hello", u8array, 2); console.log(u8array.join()); // 0,0,104,101,108,108,111,0 · To convert a JavaScript string s, the output space needed for full conversion is never less than s.length bytes and never greater than s.length * 3 bytes.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › 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.
🌐
GitHub
gist.github.com › av01d › e60f6edf3c5be6cd403eabb3d1f838f4
Convert base64 string to Uint8Array (one liner) · GitHub
Convert base64 string to Uint8Array (one liner) Raw · convertDataURItoBinary.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
github.com › achingbrain › uint8arrays
GitHub - achingbrain/uint8arrays: Utility methods for dealing with Uint8Arrays · GitHub
Returns a new Uint8Array created from the passed string and interpreted as the passed encoding.
Author: achingbrain
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>
🌐
GitHub
github.com › gnipbao › iblog › issues › 16
Uint8Array to string in JavaScript · Issue #16 · gnipbao/iblog
November 7, 2017 - * * @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); } ... // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt /* utf.js - UTF-8 <=> UTF-16 convertion * * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp> * Version: 1.0 * LastModified: Dec 25 1999 * This library is free.
Author: gnipbao
🌐
GitHub
gist.github.com › skratchdot › e095036fad80597f1c1a
Array Buffer -> String and String -> ArrayBuffer conversions in javascript · GitHub
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. ... const byteArrayStringA = String.fromCharCode.apply(null, Array.from(new Uint8Array(anArrayBufferA)));
🌐
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 - This method is not generic and can only be called on typed array instances. js · const uint8 = new Uint8Array([1, 2, 3]); // Explicit conversion console.log(uint8.toString()); // 1,2,3 // Implicit conversion console.log(`${uint8}`); // 1,2,3 · JavaScript typed arrays guide ·
🌐
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