Open In App

JavaScript Program to Convert String to Bytes

In this article, we are going to learn ho to Convert String to bytes in JavaScript. Converting a string to bytes in JavaScript involves encoding the characters using a specific character encoding (such as UTF-8) to represent the string as a sequence of bytes.

There are several methods that can be used to Convert String to bytes in JavaScript, which are listed below:



We will explore all the above methods along with their basic implementation with the help of examples.

Approach 1: Using for Loop

In this approach, we are using for loop to iterate our given string characters and then converting each character to its Unicode points by using the charAt() method.



Syntax:

for (statement 1 ; statement 2 ; statement 3){
code here...
};

Example: In this example, the stringToBytes function iterates through the characters of a given string using a for loop, converting each character to its Unicode code point by using charCodeAt(). and storing them in an array.




function stringToBytes(val) {
    const result = [];
    for (let i = 0; i < val.length; i++) {
        result.push(val.charCodeAt(i));
    }
    return result;
}
  
const str1 = "Geeks";
const result = stringToBytes(str1);
console.log(result);

Output
[ 71, 101, 101, 107, 115 ]

Approach 2: Using Array.from() Method

Using Array.from() to create an array from an iterable (like a string), with the provided mapping function converting each character to its Unicode code point.

Syntax:

Array.from(object, mapFunction, thisValue)

Example: In this example, we are using above-explained approach.




let str1 = "Geeks";
let result = Array.from(str1, char => char.charCodeAt(0));
console.log(result);

Output
[ 71, 101, 101, 107, 115 ]

Approach 3: Using TextEncoder API

In this approach,The TextEncoder API in JavaScript encodes a string into bytes, providing a byte representation using UTF-8 encoding,

Syntax:

let str = encoder.encode( str );

Example: In this example we are using the above explained method.




const str1 = "Geeks";
const encoder = new TextEncoder();
const result = encoder.encode(str1);
console.log(result);

Output
Uint8Array(5) [ 71, 101, 101, 107, 115 ]


Article Tags :