This post will discuss how to convert a string to bytes in JavaScript.

There are several ways to convert a string to bytes in JavaScript, depending on the format of the string and the desired output of the bytes. Here are some of the most common functions:

1. Using TextEncoder() constructor

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 object, which represents an array of 8-bit unsigned integers. For example, we can convert a string to bytes using TextEncoder() and encode() like this:

Download  Run Code

2. Using Buffer.from() function

Another way is to use the Buffer.from() function, which creates a new Buffer object from a string argument. The Buffer object is a Node.js-specific class that represents a fixed-length sequence of bytes. We can specify the encoding of the string as the second argument of the Buffer.from() function. For example, we can convert a string to bytes using Buffer.from() like this:

Download  Run Code

 
This function only works in Node.js and not in the browser.

3. Using charCodeAt() function

A third way is to use a for loop with the charCodeAt() function of the string object. The charCodeAt() function returns the Unicode value of the character at a given index in the string. We can use this function to get the Unicode value of each character in the string and push it into an array. For example, we can convert a string to bytes using a for loop and charCodeAt() like this:

Download  Run Code

That’s all about converting a string to bytes in JavaScript.