2021 年 8 月 21 日

TextDecoder 和 TextEncoder

如果二進制資料實際上是字串會如何?例如,我們收到一個包含文字資料的檔案。

內建的 TextDecoder 物件允許我們將值讀取到實際的 JavaScript 字串中,並提供緩衝區和編碼。

我們首先需要建立它

let decoder = new TextDecoder([label], [options]);
  • 標籤 – 編碼,預設為 utf-8,但 big5windows-1251 和許多其他編碼也受支援。
  • 選項 – 選擇性物件
    • 致命 – 布林值,如果為 true,則對無效(無法解碼)字元擲回例外,否則(預設)將它們替換為字元 \uFFFD
    • 忽略 BOM – 布林值,如果為 true,則忽略 BOM(一個選擇性的位元組順序 Unicode 標記),很少需要。

…然後解碼

let str = decoder.decode([input], [options]);
  • 輸入 – 要解碼的 BufferSource
  • 選項 – 選擇性物件
    • 串流 – 如果 解碼器 會重複呼叫並提供資料的區塊,則對串流解碼為 true。在這種情況下,多位元組字元偶爾會在區塊之間分割。此選項會指示 TextDecoder 記住「未完成」的字元,並在收到下一個區塊時解碼它們。

例如

let uint8Array = new Uint8Array([72, 101, 108, 108, 111]);

alert( new TextDecoder().decode(uint8Array) ); // Hello
let uint8Array = new Uint8Array([228, 189, 160, 229, 165, 189]);

alert( new TextDecoder().decode(uint8Array) ); // 你好

我們可以透過為其建立子陣列檢視來解碼緩衝區的一部分

let uint8Array = new Uint8Array([0, 72, 101, 108, 108, 111, 0]);

// the string is in the middle
// create a new view over it, without copying anything
let binaryString = uint8Array.subarray(1, -1);

alert( new TextDecoder().decode(binaryString) ); // Hello

TextEncoder

TextEncoder 執行相反的操作,將字串轉換為位元組。

語法為

let encoder = new TextEncoder();

它支援的唯一編碼是「utf-8」。

它有兩個方法

  • 編碼 (str) – 從字串傳回 Uint8Array
  • 編碼至 (str, 目標) – 將 str 編碼至 目標,而 目標 必須是 Uint8Array
let encoder = new TextEncoder();

let uint8Array = encoder.encode("Hello");
alert(uint8Array); // 72,101,108,108,111
教學課程地圖

留言

留言前請先閱讀這段文字…
  • 如果您有改善建議,請 提交 GitHub 議題 或提交 Pull Request,而不要留言。
  • 如果您看不懂文章中的某個部分,請詳細說明。
  • 若要插入幾行程式碼,請使用 <code> 標籤,若要插入多行程式碼,請將它們包在 <pre> 標籤中,若要插入超過 10 行程式碼,請使用沙盒 (plnkrjsbincodepen…)