Javascript TextDecoder 和 TextEncoder

2023-02-17 10:56 更新

如果二進(jìn)制數(shù)據(jù)實(shí)際上是一個(gè)字符串怎么辦?例如,我們收到了一個(gè)包含文本數(shù)據(jù)的文件。

內(nèi)建的 TextDecoder 對(duì)象在給定緩沖區(qū)(buffer)和編碼格式(encoding)的情況下,允許將值讀取為實(shí)際的 JavaScript 字符串。

首先我們需要?jiǎng)?chuàng)建:

let decoder = new TextDecoder([label], [options]);
  • ?label? —— 編碼格式,默認(rèn)為 ?utf-8?,但同時(shí)也支持 ?big5?,?windows-1251? 等許多其他編碼格式。
  • ?options? —— 可選對(duì)象:
    • ?fatal? —— 布爾值,如果為 ?true? 則為無(wú)效(不可解碼)字符拋出異常,否則(默認(rèn))用字符 ?\uFFFD? 替換無(wú)效字符。
    • ?ignoreBOM? —— 布爾值,如果為 ?true? 則忽略 BOM(可選的字節(jié)順序 Unicode 標(biāo)記),很少需要使用。

……然后解碼:

let str = decoder.decode([input], [options]);
  • ?input? —— 要被解碼的 ?BufferSource?。
  • ?options? —— 可選對(duì)象:
    • ?stream? —— 對(duì)于解碼流,為 true,則將傳入的數(shù)據(jù)塊(chunk)作為參數(shù)重復(fù)調(diào)用 ?decoder?。在這種情況下,多字節(jié)的字符可能偶爾會(huì)在塊與塊之間被分割。這個(gè)選項(xiàng)告訴 ?TextDecoder? 記住“未完成”的字符,并在下一個(gè)數(shù)據(jù)塊來(lái)的時(shí)候進(jìn)行解碼。

例如:

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) ); // 你好

我們可以通過(guò)為其創(chuàng)建子數(shù)組視圖來(lái)解碼部分緩沖區(qū):

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

// 該字符串位于中間
// 在不復(fù)制任何內(nèi)容的前提下,創(chuàng)建一個(gè)新的視圖
let binaryString = uint8Array.subarray(1, -1);

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

TextEncoder

TextEncoder 做相反的事情 —— 將字符串轉(zhuǎn)換為字節(jié)。

語(yǔ)法為:

let encoder = new TextEncoder();

只支持 utf-8 編碼。

它有兩種方法:

  • ?encode(str)? —— 從字符串返回 ?Uint8Array?。
  • ?encodeInto(str, destination)? —— 將 ?str? 編碼到 ?destination? 中,該目標(biāo)必須為 ?Uint8Array?。
let encoder = new TextEncoder();

let uint8Array = encoder.encode("Hello");
alert(uint8Array); // 72,101,108,108,111


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)