TextEncoder/TextDecoder というのをみつけた
- カテゴリ:
- JavaScript
- コメント数:
- Comments: 1
◆ String <--> Uint8Array 変換
◆ UTF-8 のみの対応
◆ UTF-8 のみの対応
いつのまにか TextEncoder と TextDecoder という関数が増えていました
Encoder では文字列をバイナリ(Uint8Array)に Decoder では バイナリ(Uint8Array) を文字列に変換できます
エンコードは utf-8 のみが対象です
少し前まで utf-8, utf-16 be, utf-16 le の 3 種類あって
という結果だったのですが 今では引数に何を入れても encoding は utf-8 固定です
ASCII 選べなくて UTF-8 固定なので charCodeAt/fromCharCode で扱うバイナリ文字列変換の代わりにはなれません
Uint8Array に適当に連番を入れて String.fromCharCode で文字列化したあとに TextEncoder を使って Uint8Array に戻したものです
300 だった長さが 428 に増えてます
UTF-8 なので 1 バイトだけじゃなく 3バイトや 4 バイトという文字もあって 1 バイトずつ 1 文字とみなさないからです
ここで活躍できるかなと思ったのにダメだったので使う機会ってどこだろう?
Crypto 系のサンプルでは見かけたけどこれまでにある機能ではあんまり使わないのかな
Encoder では文字列をバイナリ(Uint8Array)に Decoder では バイナリ(Uint8Array) を文字列に変換できます
var str_uarr = Uint8Array.from("abcd".split("").map(x => x.charCodeAt()))
console.log(str_uarr)
// Uint8Array[4] [97, 98, 99, 100]
new TextDecoder().decode(str_uarr)
// abcd
new TextEncoder().encode("abcd")
// Uint8Array[4] [97, 98, 99, 100]
console.log(str_uarr)
// Uint8Array[4] [97, 98, 99, 100]
new TextDecoder().decode(str_uarr)
// abcd
new TextEncoder().encode("abcd")
// Uint8Array[4] [97, 98, 99, 100]
エンコードは utf-8 のみが対象です
少し前まで utf-8, utf-16 be, utf-16 le の 3 種類あって
new TextEncoder("utf-8")
// TextEncoder {encoding: "utf-8"}
new TextEncoder("utf-16le")
// TextEncoder {encoding: "utf-16le"}
new TextEncoder("utf-16be")
// TextEncoder {encoding: "utf-16be"}
new TextEncoder("utf-16")
// TextEncoder {encoding: "utf-16le"}
new TextEncoder("unicode")
// TextEncoder {encoding: "utf-16le"}
// TextEncoder {encoding: "utf-8"}
new TextEncoder("utf-16le")
// TextEncoder {encoding: "utf-16le"}
new TextEncoder("utf-16be")
// TextEncoder {encoding: "utf-16be"}
new TextEncoder("utf-16")
// TextEncoder {encoding: "utf-16le"}
new TextEncoder("unicode")
// TextEncoder {encoding: "utf-16le"}
という結果だったのですが 今では引数に何を入れても encoding は utf-8 固定です
ASCII 選べなくて UTF-8 固定なので charCodeAt/fromCharCode で扱うバイナリ文字列変換の代わりにはなれません
var u8 = Uint8Array.from(Array(300), (e,i) => i)
var text = Array.from(u8, e => String.fromCharCode(e)).join("")
text.length
// 300
var eu8 = new TextEncoder().encode(text)
eu8.length
// 428
var text = Array.from(u8, e => String.fromCharCode(e)).join("")
text.length
// 300
var eu8 = new TextEncoder().encode(text)
eu8.length
// 428
Uint8Array に適当に連番を入れて String.fromCharCode で文字列化したあとに TextEncoder を使って Uint8Array に戻したものです
300 だった長さが 428 に増えてます
UTF-8 なので 1 バイトだけじゃなく 3バイトや 4 バイトという文字もあって 1 バイトずつ 1 文字とみなさないからです
ここで活躍できるかなと思ったのにダメだったので使う機会ってどこだろう?
Crypto 系のサンプルでは見かけたけどこれまでにある機能ではあんまり使わないのかな