TextEncoder

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

TextEncoder 接受码位流作为输入,并提供 UTF-8 字节流作为输出。

备注: 此特性在 Web Worker 中可用。

构造函数

TextEncoder()

返回一个新构造的 TextEncoder,它默认使用 UTF-8 编码将码位流转换成字节流。

属性

TextEncoder 接口不继承任何属性。

TextEncoder.prototype.encoding 只读

总是返回 utf-8

方法

TextEncoder 接口不继承任何方法。

TextEncoder.encode()

接受一个字符串作为输入,返回一个包含 UTF-8 编码的文本的 Uint8Array

TextEncoder.encodeInto()

接受一个字符串(编码的对象)和一个目标 Uint8Array(用于放入生成的 UTF-8 编码的文本)作为输入,并且返回一个指示编码进度的对象。此方法的性能可能会比更早出现的 encode() 方法好一些。

示例

js
const encoder = new TextEncoder();
const view = encoder.encode("€");
console.log(view); // Uint8Array(3) [226, 130, 172]

规范

Specification
Encoding
# interface-textencoder

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
TextEncoder
TextEncoder() constructor
encode
encodeInto
encoding
Available in workers

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
Has more compatibility info.

参见