TextEncoder.prototype.encode
Encodes a string into a Uint8Array containing the UTF-8 encoded text
Syntax
new TextEncoder().encode(string)Parameters
| Parameter | Type | Description |
|---|---|---|
| string | string | The text string to encode |
Return Value
A Uint8Array containing the UTF-8 encoded text
Examples
const encoder = new TextEncoder()
const bytes = encoder.encode('Hello World')
console.log(bytes) // Uint8Array(11)const encoder = new TextEncoder()
const data = encoder.encode(JSON.stringify({ key: 'value' }))
console.log('Bytes:', data.byteLength)function stringToBytes(str: string): Uint8Array {
return new TextEncoder().encode(str)
}Understanding TextEncoder.prototype.encode
The TextEncoder.prototype.encode method in JavaScript encodes a string into a Uint8Array containing the UTF-8 encoded text. It belongs to the TextEncoder object and is one of the most widely used methods for working with textencoder values in modern JavaScript and TypeScript applications.
The method signature is new TextEncoder().encode(string). It accepts 1 parameter: string. When called, it returns a uint8array containing the utf-8 encoded text. Understanding when and how to use encode() helps you write more expressive, readable code.
Common use cases for TextEncoder.prototype.encode include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like textdecoder-decode, crypto-subtle-digest, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for TextEncoder.prototype.encode is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
Related Tools
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.