[[UTF-8]]の場合は[[TextEncoder]]を使う。[[UTF-16]]の場合は文字を[[String.prototype.charCodeAt]]を使って変換する。
> [!caution]
> [[UTF-16]]は[[サロゲートペア]]を考慮するため、2つの[[コードユニット]]が返却される場合があることに注意。
```ts
function toUTF8CodeUnits(str: string): string {
return Array.from(new TextEncoder().encode(str)).map((x) =>
x.toString(16).toUpperCase()
).join(" ");
}
function toUTF16CodeUnits(str: string): string {
return Array.from({ length: str.length }, (_, i) => str.charCodeAt(i))
.map((x) => x.toString(16).toUpperCase().padStart(4, "0"))
.join(" ");
}
// UTF-8
console.log(toUTF8CodeUnits("a")); // 61 (1byte)
console.log(toUTF8CodeUnits("あ")); // E3 81 82 (3byte)
console.log(toUTF8CodeUnits("😊")); // F0 9F 98 8A (4byte:1つのコードポイント)
console.log(toUTF8CodeUnits("☺️")); // E2 98 BA EF B8 8F (6byte)
// UTF-16
console.log(toUTF16CodeUnits("a")); // 0061 (2byte)
console.log(toUTF16CodeUnits("あ")); // 3042 (2byte)
console.log(toUTF16CodeUnits("😊")); // D83D DE0A (4byte:サロゲートペアなので1つのコードポイント)
console.log(toUTF16CodeUnits("☺️")); // 263A FE0F (4byte:2つのコードポイント)
```