TextEncoder.encode()

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.encode() 方法接受一个字符串作为输入,返回一个对参数中给定的文本的编码后的 Uint8Array,编码的方法通过 TextEncoder 对象指定。

语法

js
encode(string)

参数

string

一个包含了将要编码的文本。

返回值

一个 Uint8Array 对象。

示例

html
<p class="source">This is a sample paragraph.</p>
<p class="result">Encoded result:</p>
js
const sourcePara = document.querySelector(".source");
const resultPara = document.querySelector(".result");
const string = sourcePara.textContent;

const textEncoder = new TextEncoder();

let encoded = textEncoder.encode(string);
resultPara.textContent += encoded;

规范

Specification
Encoding Standard
# ref-for-dom-textencoder-encode①

浏览器兼容性

BCD tables only load in the browser

参见