TextEncoder.prototype.encode()

TextEncoder.prototype.encode() 方法接受一个 USVString 作为参数,返回一个以给定的文本(字符串)参数,通过 TextEncoder 中指定的方法(默认 UTF-8)编码后的 Uint8Array 类型的值。

语法

b1 = encoder.encode(string);

参数

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

返回值

一个 Uint8Array 对象。

示例

<p class="source">This is a sample paragraph.</p>
<p class="result">Encoded result: </p>
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 Status Comment
Encoding
TextEncoder.prototype.encode()
Living Standard Initial definition.

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
encode
Experimental
Chrome Full support 38Edge Full support 79Firefox Full support 19
Full support 19
Full support 18
Notes
Notes Firefox 18 implemented an earlier and slightly different version of the specification.
IE No support NoOpera Full support 25Safari Full support 10.1WebView Android Full support 38Chrome Android Full support 38Firefox Android Full support 19
Full support 19
Full support 18
Notes
Notes Firefox 18 implemented an earlier and slightly different version of the specification.
Opera Android Full support YesSafari iOS Full support 10.3Samsung Internet Android Full support 3.0

Legend

Full support  
Full support
No support  
No support
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.
See implementation notes.
See implementation notes.

另见