Update 2018 - The easiest way in 2018 should be TextEncoder

let utf8Encode = new TextEncoder();
utf8Encode.encode("abc");
// Uint8Array [ 97, 98, 99 ]

Caveats - The returned element is a Uint8Array, and not all browsers support it.

Answer from code4j on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-program-to-convert-string-to-bytes
JavaScript Program to Convert String to Bytes - GeeksforGeeks
July 23, 2025 - ... Example: In this example, we are using above-explained approach. ... In this approach,The TextEncoder API in JavaScript encodes a string into bytes, providing a byte representation using UTF-8 encoding,
Discussions

java - Convert string to byte array in frida js script - Reverse Engineering Stack Exchange
I am having an issue with a JavaScript script to be executed in Frida. In this case, I am intercepting an input from a function where I receive an array of bytes. I need to convert this array to a string, modify it, and then convert it back to an array of bytes before returning the value. More on reverseengineering.stackexchange.com
🌐 reverseengineering.stackexchange.com
March 6, 2024
Reading bytes from a JavaScript string - Stack Overflow
The problem is that strings in JavaScript are UTF-16 (instead of ASCII) and charCodeAt often returns values higher than 256. The Mozilla reference states that "The first 128 Unicode code points are a direct match of the ASCII character encoding." (what about ASCII values > 128?). How can I convert the result of charCodeAt to an ASCII value? Or is there a better way to convert a string of four characters to a 4 byte ... More on stackoverflow.com
🌐 stackoverflow.com
Bug converting string to bytes32
Maybe you're aware of this but I did some investigating in Remix to understand the issue. It seems memory is structured into 32 byte slots. Arrays consist of a 32 byte slot that represents it's size (length) in whatever the type specifies (eg, a string is a byte array, so the size is how many individual bytes the array is made up of, alternatively for a uint256[] array which consists of 32 byte slots, the size is how many 32 byte slots it takes up) followed by 32 byte chunks of the bytes of the data (as many 32 byte slots as is required to store the whole length of the array). This means that if you pass an empty string or pass nothing, the first 32 byte slot of the string (length) is 0 and the following 32 byte slot which would hold the first 32 bytes of the data has nothing to go in it so will just be used for the next thing stored in memory (which is what will be loaded by the assembly code). There's no point reserving an empty 32 byte slot for no data. More on reddit.com
🌐 r/ethdev
6
6
November 9, 2017
Is there a way to encode raw bytes in Shift-JIS?
It seems like the array data is a double-encoded text. e.g. Shift-JIS then GB2312, or GB2312 then Shift-JIS. My guess is Shift-JIS then GB2312. i.e. originally a Shift-JIS encoded text, then wrapped with GB2312 encoding. Note: GB2312 character set also includes Japanese katakana characters. More on reddit.com
🌐 r/learnjavascript
4
5
April 2, 2016
People also ask

How do I run JavaScript locally vs in the browser?
In the browser: open DevTools (F12), Console tab, paste code, Enter. For HTML pages, add a script tag pointing to your .js file. Locally: install Node.js (LTS), then node script.js in your terminal from the file folder.
🌐
itsourcecode.com
itsourcecode.com › home › how to convert string to byte array in javascript?
How to Convert String to Byte Array in JavaScript (2026)
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds top-level await, private class fields with #, and the .at() array method. For older browsers, transpile with Babel or use Vite, esbuild, or webpack.
🌐
itsourcecode.com
itsourcecode.com › home › how to convert string to byte array in javascript?
How to Convert String to Byte Array in JavaScript (2026)
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard with IntelliSense, debugger, terminal, Git, and a huge extension marketplace. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
🌐
itsourcecode.com
itsourcecode.com › home › how to convert string to byte array in javascript?
How to Convert String to Byte Array in JavaScript (2026)
🌐
GitHub
gist.github.com › lihnux › 2aa4a6f5a9170974f6aa
Javascript Convert String to Byte Array · GitHub
String.charCodeAt() returns a 16 bit unsigned integer, it must be split into two bytes if exceeds 0xff · Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
🌐
Reddit
reddit.com › r/javascripttips › how to convert string to byte array in javascript?
r/JavaScriptTips on Reddit: How to Convert String to Byte Array in JavaScript?
May 1, 2023 - This object provides a view of an underlying ArrayBuffer object, which represents a fixed-length, contiguous block of memory. To convert a JavaScript string to a byte array, we can use the TextEncoder interface.
🌐
Designcise
designcise.com › web › tutorial › how-to-convert-a-javascript-string-to-a-byte-array
How to Convert a JavaScript String to a Byte Array? - Designcise
April 9, 2023 - In JavaScript, you can convert a string to an array of bytes by using the TextEncoder API, for example, in the following way: function toBytesArray(str) { const encoder = new TextEncoder(); return encoder.encode(str); } console.log(toBytesA...
🌐
Techie Delight
techiedelight.com › home › java › convert a string to bytes in javascript
Convert a string to bytes in JavaScript | Techie Delight
July 7, 2026 - One way is to use the TextEncoder() constructor, which creates a TextEncoder object that can encode a string into a byte stream with UTF-8 encoding. We can use the encode() function of the TextEncoder object to convert a string to a Uint8Array ...
Find elsewhere
🌐
DEV Community
dev.to › rajnishkatharotiya › get-byte-size-of-the-string-in-javascript-20jm
Get Byte size of the string in Javascript - DEV Community
April 12, 2020 - In this series, I’m going to talk about some shortcodes and useful functions of javascript. These snippets can help you to make your development more efficient and faster. Stay tuned till the end to learn something new… 😊 · As we all know a byte is one the unit of digital information, and while development taking care of the size of variables, records and files are a much important task. To do that we have various ways but with these functions, it’s very easy to do. byteSize() snippet will take a string as an input and in the output, it’ll return byte size of a given string.
🌐
Itsourcecode
itsourcecode.com › home › how to convert string to byte array in javascript?
How to Convert String to Byte Array in JavaScript (2026)
July 9, 2026 - We then delved into the step-by-step process of converting a string into a byte array using the TextEncoder object in JavaScript. We created an instance of TextEncoder, defined our string, used the encode method to convert the string into bytes, and finally logged the byte array to the console.
🌐
W3Resource
w3resource.com › javascript-exercises › fundamental › javascript-fundamental-exercise-13.php
JavaScript fundamental (ES6 Syntax): Convert the length of a given string in bytes - w3resource
July 3, 2025 - Use Blob.size to get the length of the string in bytes. ... //#Source https://bit.ly/2neWfJ2 // Define a function called `byte_Size` that calculates the byte size of a string. const byte_Size = str => new Blob([str]).size; // Test the function ...
🌐
GitHub
gist.github.com › robingenz › 5736ffd3d2f23966eabec721bb03133e
String to byte array converter in JavaScript · GitHub
String to byte array converter in JavaScript. GitHub Gist: instantly share code, notes, and snippets.
🌐
CodePal
codepal.ai › code generator › javascript string to bytes
JavaScript String to Bytes - CodePal
April 28, 2023 - Note that this function requires a modern browser that supports the TextEncoder API. ... function stringToBytes(str) { // Create a new TextEncoder instance const encoder = new TextEncoder(); // Encode the string as a Uint8Array const bytes = ...
🌐
Online String Tools
onlinestringtools.com › convert-string-to-bytes
Convert a String to Bytes – Online String Tools
Select this option to add a whitespace char after each byte. This browser-based program converts a string to a byte array. The string is split into individual characters and then for each character, the program finds its byte representation, and prints it in the output area in the hexadecimal base.
🌐
Basedash
admin.basedash.com › blog › javascript-string-to-bytes
Javascript: string to bytes | Basedash
This guide walks you through how to convert a JavaScript string to bytes.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-get-the-length-of-a-string-in-bytes-in-javascript
How to Get the Length of a String in Bytes in JavaScript ? - GeeksforGeeks
June 24, 2024 - The TextEncoder API provides an efficient way to encode a string into a specific format (e.g., UTF-8) and retrieve its byte length.
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › string › byte size of string
Calculate the byte size of a JavaScript string - 30 seconds of code
March 9, 2024 - This is especially important when ... we can convert the string into a Blob object, and then use the Blob.size property to get the byte size of the string....
🌐
GitHub
gist.github.com › raphaelchaib › 0eb1bebd5142eab4b099159d3d35d22a
Javascript: String to Bytes array · GitHub
August 16, 2016 - 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.
🌐
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 - 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.
Top answer
1 of 9
40

I believe that you can can do this with relatively simple bit operations:

function stringToBytes ( str ) {
  var ch, st, re = [];
  for (var i = 0; i < str.length; i++ ) {
    ch = str.charCodeAt(i);  // get char 
    st = [];                 // set up "stack"
    do {
      st.push( ch & 0xFF );  // push byte to stack
      ch = ch >> 8;          // shift value down by 1 byte
    }  
    while ( ch );
    // add stack contents to result
    // done because chars have "wrong" endianness
    re = re.concat( st.reverse() );
  }
  // return an array of bytes
  return re;
}

stringToBytes( "A\u1242B\u4123C" );  // [65, 18, 66, 66, 65, 35, 67]

It should be a simple matter to sum the output up by reading the byte array as if it were memory and adding it up into larger numbers:

function getIntAt ( arr, offs ) {
  return (arr[offs+0] << 24) +
         (arr[offs+1] << 16) +
         (arr[offs+2] << 8) +
          arr[offs+3];
}

function getWordAt ( arr, offs ) {
  return (arr[offs+0] << 8) +
          arr[offs+1];
}

'\\u' + getWordAt( stringToBytes( "A\u1242" ), 1 ).toString(16);  // "1242"
2 of 9
17

Borgar's answer seems correct.

Just wanted to clarify one point. Javascript treats bitwise operations as '32-bit signed int's, where the last (left-most) bit is the sign bit. Ie,

getIntAt([0x7f,0,0,0],0).toString(16)  //  "7f000000"

getIntAt([0x80,0,0,0],0).toString(16)  // "-80000000"

However, for octet-data processing (eg, network stream, etc), usually want the 'unsigned int' representation. This can be accomplished by adding a '>>> 0' (zero-fill right-shift) operator which internally tells Javascript to treat this as unsigned.

function getUIntAt ( arr, offs ) {
  return (arr[offs+0] << 24) +
         (arr[offs+1] << 16) +
         (arr[offs+2] << 8) +
          arr[offs+3] >>> 0;
}

getUIntAt([0x80,0,0,0],0).toString(16)   // "80000000"