Uint8ArrayEncodeTextWithIcons.js
· 1.2 KiB · JavaScript
Raw
function encodeTextWithIcons(text) {
// Split text by icon pattern {number}
const parts = text.split(/(\{\d+\})/g);
const byteArray = [];
for (const part of parts) {
if (part === '') continue;
// Check if it's an icon pattern
const iconMatch = part.match(/^\{(\d+)\}$/);
if (iconMatch) {
// It's an icon - add the icon number as a byte
const iconNumber = parseInt(iconMatch[1]);
byteArray.push(iconNumber);
} else {
// It's regular text - convert each character to byte
for (let i = 0; i < part.length; i++) {
byteArray.push(part.charCodeAt(i));
}
}
}
return new Uint8Array(byteArray);
}
// Example usage:
const text = "Hello {133} World {255} Test";
const encoded = encodeTextWithIcons(text);
console.log("Original:", text);
console.log("Byte Array:", Array.from(encoded));
console.log("Uint8Array:", encoded);
```
**Output example:**
```
Original: Hello {133} World {255} Test
Byte Array: [72, 101, 108, 108, 111, 32, 133, 32, 87, 111, 114, 108, 100, 32, 255, 32, 84, 101, 115, 116]
| 1 | function encodeTextWithIcons(text) { |
| 2 | // Split text by icon pattern {number} |
| 3 | const parts = text.split(/(\{\d+\})/g); |
| 4 | |
| 5 | const byteArray = []; |
| 6 | |
| 7 | for (const part of parts) { |
| 8 | if (part === '') continue; |
| 9 | |
| 10 | // Check if it's an icon pattern |
| 11 | const iconMatch = part.match(/^\{(\d+)\}$/); |
| 12 | |
| 13 | if (iconMatch) { |
| 14 | // It's an icon - add the icon number as a byte |
| 15 | const iconNumber = parseInt(iconMatch[1]); |
| 16 | byteArray.push(iconNumber); |
| 17 | } else { |
| 18 | // It's regular text - convert each character to byte |
| 19 | for (let i = 0; i < part.length; i++) { |
| 20 | byteArray.push(part.charCodeAt(i)); |
| 21 | } |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | return new Uint8Array(byteArray); |
| 26 | } |
| 27 | |
| 28 | // Example usage: |
| 29 | const text = "Hello {133} World {255} Test"; |
| 30 | const encoded = encodeTextWithIcons(text); |
| 31 | |
| 32 | console.log("Original:", text); |
| 33 | console.log("Byte Array:", Array.from(encoded)); |
| 34 | console.log("Uint8Array:", encoded); |
| 35 | ``` |
| 36 | |
| 37 | **Output example:** |
| 38 | ``` |
| 39 | Original: Hello {133} World {255} Test |
| 40 | Byte Array: [72, 101, 108, 108, 111, 32, 133, 32, 87, 111, 114, 108, 100, 32, 255, 32, 84, 101, 115, 116] |