EN
TypeScript - convert string to bytes array
0
points
In this short article, we would like to show, how using TypeScript, convert string to bytes array.
Hint: below solution works under web browser and Node.js TypeScript.
Practical example
const toBytes = (text: string): number[] => {
const surrogate = encodeURIComponent(text);
const result = [];
for (let i = 0; i < surrogate.length; ) {
const character = surrogate[i];
i += 1;
if (character == '%') {
const hex = surrogate.substring(i, (i += 2));
if (hex) {
result.push(parseInt(hex, 16));
}
} else {
result.push(character.charCodeAt(0));
}
}
return result;
};
// Usage example:
const bytes: number[] = toBytes('Some text here...'); // converts string to UTF-8 bytes
console.log(bytes);
Output:
[83, 111, 109, 101, 32, 116, 101, 120, 116, 32, 104, 101, 114, 101, 46, 46, 46]