TextEncoder: convert text to UTF-8 bytes
Quick answer
TextEncoder converts JavaScript strings into UTF-8 bytes. UTF-16 string length is not the same as encoded byte length.
How it works
new TextEncoder().encode(text) returns a Uint8Array. encodeInto(source,destination) writes into a supplied Uint8Array and returns read (UTF-16 code units consumed) and written (bytes produced). It does not write a partial encoded code point. A lone surrogate is converted to the replacement character before encoding.
Local examples
Run in a fresh browser document. Uses synthetic local data; actual ByteMind editor support is unverified.
(async () => {const b=new TextEncoder().encode("Aé");console.log(JSON.stringify([...b]));})()Expected console output:
[65,195,169]ASCII A uses one byte and é uses two.
Run in a fresh browser document. Uses synthetic local data; actual ByteMind editor support is unverified.
(async () => {const dst=new Uint8Array(2);const r=new TextEncoder().encodeInto("Aé",dst);console.log(r.read,r.written,JSON.stringify([...dst]));})()Expected console output:
1 1 [65,0]The two-byte character cannot fit after A.
Common mistakes
Do not use charCodeAt as a general UTF-8 encoder. Check encodeInto progress when the destination is small.
Practice
Encode ASCII, Persian text and an emoji; compare their string lengths and byte lengths.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
TextEncoder: convert text to UTF-8 bytes — Knowledge Check
Apply the concept and reason about local example output.
Which encoding does TextEncoder produce?
What does encodeInto.read count?
Will encodeInto write half of a multibyte UTF-8 character?
What is the expected console output of TextEncoder: convert text to UTF-8 bytes example 1?
(async () => {const b=new TextEncoder().encode("Aé");console.log(JSON.stringify([...b]));})()What is the expected console output of TextEncoder: convert text to UTF-8 bytes example 2?
(async () => {const dst=new Uint8Array(2);const r=new TextEncoder().encodeInto("Aé",dst);console.log(r.read,r.written,JSON.stringify([...dst]));})()