Table of Contents
UTF-8エンコード
TextEncoder.prototype.encode()
TextEncoderオブジェクトを生成、encodeメソッドにUSVString値を渡すと、エンコードされたUint8Arrayが返ってきます。
1 2 3 | const encoder = new TextEncoder(); const encoded = encoder.encode( 'A' ); console.log(encoded); |
TextEncoder.prototype.encodeInto()
現在Experimentalなメソッドですが、引数にエンコードするUSVString値の他、エンコード後の値を格納するUint8Arrayも渡すencodeIntoもあります。
こちらは戻り値にread, writtenの2つのメンバを持つdictionaryが返ってきます。
readにはUTF-8へ変換されたソースのUTF-16単位のコード数が、
writtenには出力先Uint8Arrayの中で変更されたバイト数が格納されています。
1 2 3 4 5 6 | const encoder = new TextEncoder; let u8array = new Uint8Array(4); let ret = encoder.encodeInto( "A" , u8array); console.log( "read : " + ret.read); console.log( "written : " + ret.written); console.log(u8array); |
UTF-8以外のエンコード
https://github.com/inexorabletash/text-encoding
リンク
TextEncoder – Web API | MDN
https://developer.mozilla.org/ja/docs/Web/API/TextEncoder