TextEncoder.encode()

我们的志愿者还没有将这篇文章翻译为 中文 (简体)加入我们帮助完成翻译
您也可以阅读此文章的English (US)版。

The TextEncoder.encode() method takes a USVString as input, and returns a Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object.

Syntax

b1 = encoder.encode(string);

Parameters

string
Is a USVString containing the text to encode.

Return value

A Uint8Array object.

Examples

<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;

Polyfill

The next function represents a workaround for TextEncoder.encode(str) in IE9+ browsers:

function CustomTextEncoder(str) {
    var buf       = new ArrayBuffer(str.length);
    var bufView8  = new Uint8Array(buf);
    for (var i=0, strLen=str.length; i < strLen; i++) {
        bufView8[i] = str.charCodeAt(i);
    }
    return bufView8;
}

Specifications

Specification Status Comment
Encoding
The definition of 'TextEncoder.encode()' in that specification.
Living Standard Initial definition.

Browser compatibility

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
encode
Experimental
Chrome Full support 38Edge ? Firefox 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 38Edge Mobile ? Firefox 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 ? Safari iOS Full support 10.1Samsung Internet Android ?

Legend

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

See also

文档标签和贡献者

最后编辑者: mdnwebdocs-bot,