-
Notifications
You must be signed in to change notification settings - Fork 23.3k
Expand file tree
/
Copy pathindex.md
More file actions
58 lines (38 loc) · 1.24 KB
/
Copy pathindex.md
File metadata and controls
58 lines (38 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
---
title: "TextEncoder: encode() method"
short-title: encode()
slug: Web/API/TextEncoder/encode
page-type: web-api-instance-method
browser-compat: api.TextEncoder.encode
---
{{APIRef("Encoding API")}}{{AvailableInWorkers}}
The **`TextEncoder.encode()`** method takes a string as input, and returns a {{jsxref("Global_Objects/Uint8Array", "Uint8Array")}} containing the string {{glossary("character encoding", "encoded")}} using {{glossary("UTF-8")}}.
## Syntax
```js-nolint
encode(string)
```
### Parameters
- `string`
- : A string containing the text to encode.
### Return value
A {{jsxref("Uint8Array")}} object containing the UTF-8 encoding of the input string.
## Examples
```html
<p class="source">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();
const encoded = textEncoder.encode(string);
resultPara.textContent = `${resultPara.textContent} ${encoded}`;
```
{{EmbedLiveSample('Examples')}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{DOMxRef("TextEncoder")}} interface it belongs to.