このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

TextDecoder

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2020年1月⁩.

TextDecoder インターフェイスは、特定のテキストエンコーディング、例えば UTF-8ISO-8859-2KOI8-RGBK などのデコーダーを表します。デコーダーは入力としてバイトストリームを受け取り、コードポイントのストリームを出力します。

メモ: この機能はウェブワーカー内で利用可能です。

コンストラクター

TextDecoder()

新たに生成した TextDecoder を返します。これは、引数で指定したデコード方式を使用して連続したコードポイントを生成します。

インスタンスプロパティ

TextDecoder インターフェイスは、何もプロパティを継承していません。

TextDecoder.encoding 読取専用

デコーダーの名称を持つ文字列であり、これは TextDecoder が使用する方式を表す文字列です。

TextDecoder.fatal 読取専用

エラーモードが fatal であるかを示す論理値です。

TextDecoder.ignoreBOM 読取専用

バイトオーダーマークを無視するかどうかを示す論理値です。

インスタンスメソッド

TextDecoder インターフェイスは、何もメソッドを継承していません。

TextDecoder.decode()

特定の TextDecoder オブジェクトの方式でデコードされたテキストを含む文字列を返します。

型付き配列でのテキスト表現

この例では、中国語/日本語の文字 「吉」を表す漢字 を、異なる 5 種類の型付き配列、 Uint8Array, Int8Array, Uint16Array, Int16Array, Int32Array で表します。

js
let utf8decoder = new TextDecoder(); // default 'utf-8' or 'utf8'

let u8arr = new Uint8Array([240, 160, 174, 183]);
let i8arr = new Int8Array([-16, -96, -82, -73]);
let u16arr = new Uint16Array([41200, 47022]);
let i16arr = new Int16Array([-24336, -18514]);
let i32arr = new Int32Array([-1213292304]);

console.log(utf8decoder.decode(u8arr));
console.log(utf8decoder.decode(i8arr));
console.log(utf8decoder.decode(u16arr));
console.log(utf8decoder.decode(i16arr));
console.log(utf8decoder.decode(i32arr));

UTF-8 ではないテキストの扱い

この例では、ロシア語の "Привет, мир!"、 "Hello, world." という意味のテキストをデコードします。 TextDecoder() コンストラクターでは、キリル語の文字に適した Windows-1251 文字エンコーディングを指定します。

js
const win1251decoder = new TextDecoder("windows-1251");
const bytes = new Uint8Array([
  207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33,
]);
console.log(win1251decoder.decode(bytes)); // Привет, мир!

仕様書

Specification
Encoding
# interface-textdecoder

ブラウザーの互換性

関連情報