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.
xxxxxxxxxx
1
const toBytes = (text: string): number[] => {
2
const surrogate = encodeURIComponent(text);
3
const result = [];
4
for (let i = 0; i < surrogate.length; ) {
5
const character = surrogate[i];
6
i += 1;
7
if (character == '%') {
8
const hex = surrogate.substring(i, (i += 2));
9
if (hex) {
10
result.push(parseInt(hex, 16));
11
}
12
} else {
13
result.push(character.charCodeAt(0));
14
}
15
}
16
return result;
17
};
18
19
20
// Usage example:
21
22
const bytes: number[] = toBytes('Some text here...'); // converts string to UTF-8 bytes
23
24
console.log(bytes);
Output:
xxxxxxxxxx
1
[83, 111, 109, 101, 32, 116, 101, 120, 116, 32, 104, 101, 114, 101, 46, 46, 46]