Convert a string to bytes in JavaScript
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:
|
1 2 3 4 5 6 7 |
var str = "Hello, world!"; var utf8EncodeText = new TextEncoder(); var bytes = utf8EncodeText.encode(str); // bytes is Uint8Array(13) [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33] console.log(bytes); |
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:
|
1 2 3 4 5 6 |
var str = "Hello, world!"; var bytes = Buffer.from(str, "utf8"); // bytes is <Buffer 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21> console.log(bytes); |
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:
|
1 2 3 4 5 6 7 8 9 10 |
var str = "Hello, world!"; var bytes = []; for (var i = 0; i < str.length; i++) { // push the Unicode value of each character into the array bytes.push(str.charCodeAt(i)); } // bytes is [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33] console.log(bytes); |
That’s all about converting a string to bytes in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)