TextDecoder

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

注意:此功能在 Web Workers 中可用。

TextDecoder 介面代表了特定文字編碼的解碼器,例如 UTF-8ISO-8859-2GBK。解碼器接收位元組陣列作為輸入,並返回一個 JavaScript 字串。

建構函式

TextDecoder()

建立並返回一個新的 TextDecoder

例項屬性

TextDecoder 介面不繼承任何屬性。

TextDecoder.encoding 只讀

一個字串,包含此 TextDecoder 將使用的字元編碼系統的名稱。

TextDecoder.fatal 只讀

一個布林值,指示錯誤模式是否為致命模式。

TextDecoder.ignoreBOM 只讀

一個布林值,指示是否忽略 位元組順序標記

例項方法

TextDecoder 介面不繼承任何方法。.

TextDecoder.decode()

將給定的位元組解碼為 JavaScript 字串並返回。

示例

解碼 UTF-8 文字

此示例展示瞭如何解碼字元“𠮷”的 UTF-8 編碼。

html
<button id="decode">Decode</button>
<button id="reset">Reset</button>
<div id="output"></div>
js
const utf8decoder = new TextDecoder(); // default 'utf-8'
const encodedText = new Uint8Array([240, 160, 174, 183]);

const output = document.querySelector("#output");
const decodeButton = document.querySelector("#decode");
decodeButton.addEventListener("click", () => {
  output.textContent = utf8decoder.decode(encodedText);
});

const resetButton = document.querySelector("#reset");
resetButton.addEventListener("click", () => {
  window.location.reload();
});

解碼非 UTF-8 文字

在此示例中,我們解碼俄語文字“Привет, мир!”,其含義為“你好,世界。”。在我們的 TextDecoder() 建構函式中,我們指定了 Windows-1251 字元編碼。

html
<button id="decode">Decode</button>
<button id="reset">Reset</button>
<div id="decoded"></div>
js
const win1251decoder = new TextDecoder("windows-1251");
const encodedText = new Uint8Array([
  207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33,
]);

const decoded = document.querySelector("#decoded");
const decodeButton = document.querySelector("#decode");
decodeButton.addEventListener("click", () => {
  decoded.textContent = win1251decoder.decode(encodedText);
});

const resetButton = document.querySelector("#reset");
resetButton.addEventListener("click", () => {
  window.location.reload();
});

規範

規範
編碼
# interface-textdecoder

瀏覽器相容性

另見