Unicode and encodings
suggest changeText in a Node.js program lives in two forms:
- strings are sequences of UTF-16 code units. That's how JavaScript defines them, and it's why
'😀'.lengthis2. - bytes (
Buffer,Uint8Array) are what files, sockets, HTTP bodies and child processes deal in. To turn bytes into a string you must know their encoding, almost always UTF-8.
Most Unicode bugs come from mixing up the units: counting code units when you meant characters, decoding a chunk that ends in the middle of a character, or decoding bytes with the wrong encoding.
A few terms used below:
| Term | Meaning | Example |
|---|---|---|
| code point | a number assigned to a character, written U+XXXX | é is U+00E9, 😀 is U+1F600 |
| code unit | 16-bit unit of a JavaScript string | 😀 is 2 code units |
| surrogate pair | two code units encoding one code point above U+FFFF | 😀 is D83D DE00 |
| grapheme | what a user sees as one character | 👨👩👧 is 1 grapheme, 5 code points |
| encoding | how code points become bytes | UTF-8, UTF-16LE, Windows-1252 |
The examples were run with Node.js 24 (ICU 78, Unicode 17) and iconv-lite 0.7, in a project whose package.json has "type": "module".
Length: code units, code points, bytes
length and indexing work on UTF-16 code units, not characters:
const s = 'héllo 😀';
console.log(s.length); // UTF-16 code units
console.log([...s].length); // code points
console.log(Buffer.byteLength(s, 'utf8')); // bytes in UTF-8
// the emoji occupies indexes 6 and 7: a surrogate pair
console.log(s.charCodeAt(6).toString(16), s.charCodeAt(7).toString(16));
console.log(s.codePointAt(6).toString(16)); // the whole code point
console.log(JSON.stringify(s[6])); // half an emoji: a lone surrogate
console.log(s.slice(0, 7)); // slicing can cut a character in half
8
7
11
d83d de00
1f600
"\ud83d"
héllo �
Spreading a string ([...s]), for...of and Array.from(s) iterate by code point, so they never split a surrogate pair. charCodeAt(), s[i], slice() and substring() work on code units and can.
For limits that matter to storage (a database column, a protocol field, an HTTP header) count bytes with Buffer.byteLength(), not length.
Writing code points in source
const a = '\u00e9'; // é as a single code point
const b = 'e\u0301'; // e + combining acute accent
const c = '\u{1F600}'; // 😀, needs braces: beyond U+FFFF
const d = '\uD83D\uDE00'; // the same emoji written as a surrogate pair
console.log(a, b, c, d);
console.log(c === d);
console.log(String.fromCodePoint(0x1F600) === c);
console.log('U+' + 'é'.codePointAt(0).toString(16).toUpperCase().padStart(4, '0'));
é é 😀 😀
true
true
U+00E9
a and b look identical but are different strings. See the Normalization section below.
Use String.fromCodePoint() and codePointAt(). The older String.fromCharCode() and charCodeAt() only handle 16-bit code units.
How characters become bytes
UTF-8 uses 1 to 4 bytes per code point and is ASCII-compatible. UTF-16 uses 2 or 4 bytes:
for (const ch of 'aé€😀') {
const cp = ch.codePointAt(0);
const utf8 = Buffer.from(ch, 'utf8');
const utf16 = Buffer.from(ch, 'utf16le');
console.log(
ch,
'U+' + cp.toString(16).toUpperCase().padStart(4, '0'),
'length:', ch.length,
'utf8:', utf8.toString('hex'),
'utf16le:', utf16.toString('hex'),
);
}
a U+0061 length: 1 utf8: 61 utf16le: 6100
é U+00E9 length: 1 utf8: c3a9 utf16le: e900
€ U+20AC length: 1 utf8: e282ac utf16le: ac20
😀 U+1F600 length: 2 utf8: f09f9880 utf16le: 3dd800de
Graphemes: what users call characters
Many visible characters are made of several code points: letters with combining accents, flags (two regional indicator letters), and emoji sequences joined with ZERO WIDTH JOINER (U+200D). Intl.Segmenter splits text into graphemes:
const family = '👨\u200D👩\u200D👧'; // man, ZWJ, woman, ZWJ, girl
const flag = '🇵🇱'; // two "regional indicator" letters: P L
const accented = 'e\u0301'; // e + combining acute accent
const segmenter = new Intl.Segmenter('en', { granularity: 'grapheme' });
for (const s of [family, flag, accented]) {
const count = [...segmenter.segment(s)].length;
console.log(s, 'length:', s.length, 'code points:', [...s].length, 'graphemes:', count);
}
👨👩👧 length: 8 code points: 5 graphemes: 1
🇵🇱 length: 4 code points: 2 graphemes: 1
é length: 2 code points: 2 graphemes: 1
Use graphemes whenever text is shown to people: reversing, truncating with an ellipsis, enforcing a "max 20 characters" rule on a user name, or moving a cursor:
const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
function graphemes(s) {
return Array.from(segmenter.segment(s), (x) => x.segment);
}
function truncate(s, max) {
const g = graphemes(s);
return g.length <= max ? s : g.slice(0, max - 1).join('').trimEnd() + '…';
}
const text = 'Café 👨\u200D👩\u200D👧 🇵🇱!';
console.log([...text].reverse().join('')); // breaks the emoji
console.log(graphemes(text).reverse().join('')); // correct
console.log(text.slice(0, 8)); // cuts the family apart
console.log(truncate(text, 8));
!🇱🇵 👧👩👨 éfaC
!🇵🇱 👨👩👧 éfaC
Café 👨
Café 👨👩👧…
Reversing by code point turned the Polish flag into the Lithuanian one (🇱🇵 is "LP") and reordered the family. Intl.Segmenter also supports granularity: 'word' and 'sentence', which work for languages without spaces between words, like Japanese or Thai.
TextEncoder and TextDecoder
TextEncoder and TextDecoder are the web-standard API for converting between strings and bytes. They're global in Node.js and work the same in browsers, Deno and Bun:
const encoder = new TextEncoder(); // always UTF-8
const bytes = encoder.encode('zażółć 😀');
console.log(bytes);
const decoder = new TextDecoder(); // 'utf-8' by default
console.log(decoder.decode(bytes));
// Buffer is a Uint8Array subclass, so the two interoperate
const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
console.log(buf.toString('utf8') === decoder.decode(bytes));
// encodeInto() writes into an existing array, without allocating
const target = new Uint8Array(8);
console.log(encoder.encodeInto('zażółć 😀', target));
Uint8Array(15) [
122, 97, 197, 188, 195,
179, 197, 130, 196, 135,
32, 240, 159, 152, 128
]
zażółć 😀
true
{ read: 5, written: 8 }
encodeInto() stopped after 5 code units (zażół) because the next character didn't fit in the remaining space. It never writes a partial character.
TextEncoder only produces UTF-8. TextDecoder can decode many encodings (see the Legacy encodings section).
Encodings supported by Buffer
Buffer.from(string, encoding) and buf.toString(encoding) support a fixed set of encodings: 'utf8', 'utf16le' (alias 'ucs2'), 'latin1' (alias 'binary'), 'ascii', 'base64', 'base64url' and 'hex'. Names are case-insensitive and 'utf-8' works too.
const s = 'Zürich €5';
for (const enc of ['utf8', 'utf16le', 'latin1', 'ascii']) {
const buf = Buffer.from(s, enc);
console.log(enc.padEnd(8), buf.length.toString().padStart(2), buf.toString('hex').padEnd(36), JSON.stringify(buf.toString(enc)));
}
console.log(Buffer.isEncoding('UTF-8'), Buffer.isEncoding('ucs2'), Buffer.isEncoding('windows-1252'));
utf8 12 5ac3bc7269636820e282ac35 "Zürich €5"
utf16le 18 5a00fc0072006900630068002000ac203500 "Zürich €5"
latin1 9 5afc7269636820ac35 "Zürich ¬5"
ascii 9 5afc7269636820ac35 "Z|rich ,5"
true true false
latin1 and ascii silently keep only the low 8 bits of each code unit, so € (U+20AC) became byte 0xac, and the round trip lost data without any error. ascii decoding also clears the high bit of each byte. Use them only for data you know is in that range. base64, base64url and hex are binary-to-text encodings, covered in Base64 and hex encoding.
Invalid UTF-8
buf.toString('utf8') never throws: each invalid byte sequence becomes U+FFFD REPLACEMENT CHARACTER (�). That's good for logging but bad for data, because the original bytes are lost. To detect bad input, use isUtf8() or a fatal TextDecoder:
import { isUtf8 } from 'node:buffer';
const good = Buffer.from('café', 'utf8');
const bad = Buffer.from([0x63, 0x61, 0x66, 0xe9]); // 'café' saved as Latin-1
console.log(bad.toString('utf8')); // invalid bytes become U+FFFD
console.log(isUtf8(good), isUtf8(bad));
try {
new TextDecoder('utf-8', { fatal: true }).decode(bad);
} catch (err) {
console.log(err.name, err.code);
}
// a common fallback: try UTF-8, else assume Windows-1252
function decodeText(buf) {
return isUtf8(buf) ? buf.toString('utf8') : new TextDecoder('windows-1252').decode(buf);
}
console.log(decodeText(good), decodeText(bad));
caf�
true false
TypeError ERR_ENCODING_INVALID_ENCODED_DATA
café café
The fallback works well in practice because text in a legacy 8-bit encoding is very unlikely to also be valid UTF-8.
Lone surrogates
The opposite problem: a string can contain half of a surrogate pair, for example after slice() cut an emoji in half. Such a string isn't valid Unicode and can't be encoded to UTF-8 faithfully. isWellFormed() and toWellFormed() (Node.js 20+) check and repair it:
const broken = 'ab\uD83D'; // a high surrogate with nothing after it
console.log(broken.isWellFormed());
console.log(JSON.stringify(broken.toWellFormed()));
console.log(Buffer.from(broken).toString('hex')); // encoded as EF BF BD (U+FFFD)
try {
encodeURIComponent(broken);
} catch (err) {
console.log(err.name + ': ' + err.message);
}
false
"ab�"
6162efbfbd
URIError: URI malformed
Decoding chunked data
Data from files, sockets and HTTP requests arrives in chunks, and a chunk boundary can fall in the middle of a multi-byte character. Decoding each chunk separately corrupts the text:
import { StringDecoder } from 'node:string_decoder';
const bytes = Buffer.from('€uro', 'utf8'); // € is e2 82 ac
const chunks = [bytes.subarray(0, 2), bytes.subarray(2)];
// wrong: each chunk is decoded on its own
console.log(chunks.map((c) => c.toString('utf8')).join(''));
// right: StringDecoder holds on to incomplete sequences
const sd = new StringDecoder('utf8');
let out = '';
for (const c of chunks) out += sd.write(c);
out += sd.end();
console.log(out);
// the same with TextDecoder and { stream: true }
const td = new TextDecoder();
let out2 = '';
for (const c of chunks) out2 += td.decode(c, { stream: true });
out2 += td.decode();
console.log(out2);
��uro
€uro
€uro
With streams you rarely need either directly. Pass an encoding option (or call stream.setEncoding('utf8')) and the stream decodes for you, or pipe a web stream through TextDecoderStream:
import { createReadStream } from 'node:fs';
import { writeFile } from 'node:fs/promises';
import { Readable } from 'node:stream';
await writeFile('greek.txt', 'Καλημέρα κόσμε');
// tiny chunks to make the problem visible
let naive = '';
for await (const chunk of createReadStream('greek.txt', { highWaterMark: 3 })) {
naive += chunk.toString('utf8');
}
console.log(naive);
// with an encoding, the stream decodes with a StringDecoder internally
let decoded = '';
for await (const chunk of createReadStream('greek.txt', { highWaterMark: 3, encoding: 'utf8' })) {
decoded += chunk;
}
console.log(decoded);
// web streams: pipe bytes through TextDecoderStream
const web = Readable.toWeb(createReadStream('greek.txt', { highWaterMark: 3 }));
let viaWeb = '';
for await (const text of web.pipeThrough(new TextDecoderStream())) viaWeb += text;
console.log(viaWeb);
Κ��λη��έρ�� ��όσ��ε
Καλημέρα κόσμε
Καλημέρα κόσμε
The bug in the first loop is easy to miss: with the default 64 KiB chunks it only shows up on large files, at random positions. The same applies to req.on('data') in an HTTP server; call req.setEncoding('utf8') or collect all chunks with Buffer.concat() and decode once. See Using Streams for more about streams.
Byte order marks
A byte order mark (BOM, U+FEFF) at the start of a file identifies its encoding. Windows tools (Excel "CSV UTF-8", older Notepad, PowerShell 5) often write one. fs.readFile(path, 'utf8') keeps it, and the invisible character ends up glued to the first word:
import { readFile, writeFile } from 'node:fs/promises';
// what Excel or Notepad may produce: UTF-8 with a byte order mark
await writeFile('bom.csv', Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from('name,city\nŁucja,Kraków\n')]));
const text = await readFile('bom.csv', 'utf8');
console.log(text.length, text.charCodeAt(0).toString(16));
console.log(text.split(',')[0] === 'name'); // the BOM is glued to the first header
const clean = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
console.log(clean.split(',')[0] === 'name');
// TextDecoder strips a BOM by default
const bytes = await readFile('bom.csv');
console.log(new TextDecoder().decode(bytes).startsWith('name'));
console.log(new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes).charCodeAt(0).toString(16));
24 feff
false
true
true
feff
The naming is confusing: ignoreBOM: true means "don't treat the BOM specially", so it stays in the output.
A BOM is also the most reliable way to recognize UTF-16 files:
import { readFile, writeFile } from 'node:fs/promises';
function detectAndDecode(buf) {
if (buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf) return ['utf-8 BOM', buf.toString('utf8', 3)];
if (buf[0] === 0xff && buf[1] === 0xfe) return ['utf-16le BOM', buf.toString('utf16le', 2)];
if (buf[0] === 0xfe && buf[1] === 0xff) return ['utf-16be BOM', new TextDecoder('utf-16be').decode(buf.subarray(2))];
return ['no BOM', buf.toString('utf8')];
}
// a UTF-16LE file with BOM, as written by PowerShell 5 or "Unicode" in Notepad
await writeFile('utf16.txt', '\ufeffПривет', 'utf16le');
const buf = await readFile('utf16.txt');
console.log(buf.subarray(0, 6));
console.log(detectAndDecode(buf));
<Buffer ff fe 1f 04 40 04>
[ 'utf-16le BOM', 'Привет' ]
When writing files, don't add a BOM to UTF-8 unless the consumer needs it. Excel is the common exception: it opens a UTF-8 CSV correctly only if it starts with '\ufeff'.
Legacy encodings
Old databases, mainframe exports, email and files from Windows applications may use encodings like Windows-1252, Windows-1250, ISO-8859-2, Shift_JIS or GBK. Official Node.js builds include full ICU data, so TextDecoder can decode all encodings from the WHATWG Encoding standard:
// bytes as legacy systems produce them
const cp1252 = Buffer.from([0x93, 0x51, 0x75, 0x6f, 0x74, 0x65, 0x94, 0x20, 0x80, 0x35]);
const sjis = Buffer.from([0x93, 0xfa, 0x96, 0x7b, 0x8c, 0xea]);
const cp1250 = Buffer.from([0x5a, 0x61, 0xbf, 0xf3, 0xb3, 0xe6]);
console.log(new TextDecoder('windows-1252').decode(cp1252));
console.log(new TextDecoder('shift_jis').decode(sjis));
console.log(new TextDecoder('windows-1250').decode(cp1250));
// Buffer's 'latin1' maps 0x80-0x9f to invisible control characters
const hex = (s) => [...s].map((c) => c.codePointAt(0).toString(16)).join(' ');
console.log(hex(cp1252.toString('latin1')));
console.log(hex(new TextDecoder('windows-1252').decode(cp1252)));
// per the WHATWG Encoding standard, 'latin1' in TextDecoder means windows-1252
console.log(new TextDecoder('latin1').encoding);
“Quote” €5
日本語
Zażółć
93 51 75 6f 74 65 94 20 80 35
201c 51 75 6f 74 65 201d 20 20ac 35
windows-1252
Text labelled "ISO-8859-1" or "Latin-1" is in practice nearly always Windows-1252 (smart quotes, €), which is why browsers and TextDecoder treat the labels as the same. Buffer's 'latin1' is the real ISO-8859-1 and gets those characters wrong.
There's no built-in way to encode to legacy encodings: TextEncoder only produces UTF-8. Use the iconv-lite package (npm install iconv-lite), which is pure JavaScript and supports both directions:
import iconv from 'iconv-lite';
const bytes = iconv.encode('Zażółć gęślą jaźń', 'windows-1250');
console.log(bytes);
console.log(iconv.decode(bytes, 'windows-1250'));
// characters that don't exist in the target encoding become '?'
console.log(iconv.encode('€ and 😀', 'iso-8859-1').toString('latin1'));
console.log(iconv.encodingExists('cp866'), iconv.encodingExists('klingon'));
<Buffer 5a 61 bf f3 b3 e6 20 67 ea 9c 6c b9 20 6a 61 9f f1>
Zażółć gęślą jaźń
? and ??
true false
iconv-lite also has iconv.decodeStream(encoding) and iconv.encodeStream(encoding) transform streams for converting large files.
A related case is the output of console programs on Windows, which use the OEM code page (for example cp437 or cp852) rather than UTF-8. Get the output of execFile() as a Buffer (encoding: 'buffer') and decode it with iconv.decode(stdout, 'cp852').
Normalization
The same visible text can be written with different code points. é can be a single code point (U+00E9, "composed") or e followed by a combining accent (U+0065 U+0301, "decomposed"). The strings look the same but aren't ===, have different lengths, and hash differently. macOS file systems, copy-paste from PDFs and some input methods produce decomposed text.
normalize() converts to a canonical form:
const nfc = 'Am\u00e9lie'; // é as one code point (what most keyboards type)
const nfd = 'Ame\u0301lie'; // e + combining accent (what macOS file names often use)
console.log(nfc, nfd, nfc === nfd, nfc.length, nfd.length);
console.log(nfc.normalize('NFC') === nfd.normalize('NFC'));
console.log(nfd.normalize('NFC').length, nfc.normalize('NFD').length);
// compatibility forms fold look-alikes into plain characters
for (const s of ['file', '①', 'Hello', 'x²']) {
console.log(s, '->', s.normalize('NFKC'));
}
// stripping accents: decompose, then drop combining marks
const slug = 'Crème Brûlée à la Française'
.normalize('NFD')
.replace(/\p{M}/gu, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-');
console.log(slug);
Amélie Amélie false 6 7
true
6 7
file -> file
① -> 1
Hello -> Hello
x² -> x2
creme-brulee-a-la-francaise
Guidelines:
- Normalize user input to NFC before storing or comparing it: user names, e-mail addresses, search terms, keys in a
Map. - NFKC is useful for identifiers and search because it folds full-width letters, ligatures and superscripts, but it changes meaning (
x²becomesx2), so don't use it on text you display. - Accent stripping with NFD only removes combining marks. Letters like
ł,øorßhave no decomposition and stay as they are; a slug library such asslugifyhandles those with transliteration tables.
Case conversion and comparison
Case mapping isn't one-to-one, and some rules depend on the language:
console.log('straße'.toUpperCase(), 'straße'.toUpperCase().length);
console.log('İstanbul'.toLowerCase().length); // i + combining dot above
console.log('istanbul'.toUpperCase(), 'istanbul'.toLocaleUpperCase('tr'));
console.log('TITLE'.toLowerCase(), 'TITLE'.toLocaleLowerCase('tr'));
const words = ['zebra', 'Äpfel', 'apple', 'Zoo', 'éclair', 'Ångström', 'ćma'];
console.log([...words].sort().join(', ')); // by UTF-16 code unit
console.log([...words].sort(new Intl.Collator('en').compare).join(', '));
console.log([...words].sort(new Intl.Collator('sv').compare).join(', '));
// accent- and case-insensitive equality
const base = new Intl.Collator('en', { sensitivity: 'base' });
console.log(base.compare('Resume', 'résumé') === 0, base.compare('a', 'b') === 0);
// natural sort of numbers inside strings
const files = ['file10.txt', 'file2.txt', 'file1.txt'];
console.log(files.sort(new Intl.Collator(undefined, { numeric: true }).compare));
STRASSE 7
9
ISTANBUL İSTANBUL
title tıtle
Zoo, apple, zebra, Äpfel, Ångström, éclair, ćma
Ångström, Äpfel, apple, ćma, éclair, zebra, Zoo
apple, ćma, éclair, zebra, Zoo, Ångström, Äpfel
true false
[ 'file1.txt', 'file2.txt', 'file10.txt' ]
What this shows:
- Converting case can change the length of a string, so never assume that
s.toUpperCase()has the same indexes ass. toUpperCase()andtoLowerCase()are locale-independent, which is what you want for identifiers, protocol keywords and HTTP headers. UsetoLocaleUpperCase(locale)only for text displayed to a user in a known language.- The default
sort()compares UTF-16 code units: all uppercase letters before lowercase, accented letters at the end. UseIntl.Collator(ora.localeCompare(b, locale)) for anything shown to people. Sorting order differs by language: in SwedishÅandÄare separate letters afterZ. - For case-insensitive comparison,
Intl.Collatorwithsensitivity: 'base'(ignores case and accents) or'accent'(ignores only case) is more correct than comparingtoLowerCase()results.
Create a collator once and reuse it; constructing one is far more expensive than calling compare(). More Intl APIs for formatting dates, numbers and plurals are covered in Node.js localization.
Regular expressions
Without the u flag, a regular expression works on code units: . matches half of an emoji and \p{...} isn't available. With u (or the newer v) it works on code points and supports Unicode property escapes:
const s = 'Łódź 2024: 😀 ok!';
console.log(s.match(/./g).length, s.match(/./gu).length); // without u, . matches half an emoji
console.log(s.match(/\p{L}+/gu)); // letters in any script
console.log(s.match(/\p{N}/gu).join(''));
console.log(/^\p{Script=Greek}+$/u.test('αβγ'), /^\p{Script=Greek}+$/u.test('abc'));
console.log(s.replace(/\p{Extended_Pictographic}/gu, '[emoji]'));
// the v flag adds set operations: letters except ASCII ones
console.log(s.match(/[\p{L}--[a-zA-Z]]/gv));
17 16
[ 'Łódź', 'ok' ]
2024
true false
Łódź 2024: [emoji] ok!
[ 'Ł', 'ó', 'ź' ]
\w, \b and \d remain ASCII-only even with the u flag, so /^\w+$/u.test('Łódź') is false. Use \p{L}, \p{N} and \p{M} (marks, needed for decomposed text) instead.
URLs and domain names
URLs can only contain ASCII. encodeURIComponent() and the URL class percent-encode the UTF-8 bytes of other characters, and host names are converted to Punycode:
import { domainToASCII, domainToUnicode } from 'node:url';
console.log(encodeURIComponent('zażółć 😀'));
console.log(decodeURIComponent('caf%C3%A9'));
const url = new URL('https://bücher.example/straße?q=naïve café');
console.log(url.href);
console.log(url.hostname, url.searchParams.get('q'));
console.log(domainToASCII('münchen.de'), domainToUnicode('xn--mnchen-3ya.de'));
za%C5%BC%C3%B3%C5%82%C4%87%20%F0%9F%98%80
café
https://xn--bcher-kva.example/stra%C3%9Fe?q=na%C3%AFve%20caf%C3%A9
xn--bcher-kva.example naïve café
xn--mnchen-3ya.de münchen.de
Don't use the deprecated punycode module; url.domainToASCII() implements the full IDNA rules, including normalization and validation.
Truncating to a byte limit
Databases and protocols often limit fields by bytes (a VARCHAR in a single-byte-charset column, a 255-byte file name, a 4 KB cookie). Cutting a Buffer at an arbitrary byte can split a character. In UTF-8, continuation bytes always look like 10xxxxxx, so back off until the cut is on a character boundary:
// truncate to at most maxBytes of UTF-8 without splitting a character
function truncateBytes(s, maxBytes) {
const buf = Buffer.from(s, 'utf8');
if (buf.length <= maxBytes) return s;
let end = maxBytes;
while (end > 0 && (buf[end] & 0xc0) === 0x80) end--; // back off continuation bytes
return buf.toString('utf8', 0, end);
}
const s = 'naïve 😀 text';
for (const n of [3, 7, 8, 9, 11]) {
const t = truncateBytes(s, n);
console.log(n, JSON.stringify(t), Buffer.byteLength(t));
}
console.log(JSON.stringify(Buffer.from(s).toString('utf8', 0, 9))); // naive cut
3 "na" 2
7 "naïve " 7
8 "naïve " 7
9 "naïve " 7
11 "naïve 😀" 11
"naïve �"
This keeps whole code points, not whole graphemes; combine it with Intl.Segmenter if the result is shown to users and may contain emoji sequences or combining marks.
Summary
- JavaScript strings are UTF-16:
length, indexes andslice()count code units. Use[...s]for code points,Intl.Segmenterfor user-visible characters andBuffer.byteLength()for bytes. - Use UTF-8 for everything you write: files, HTTP (
Content-Type: text/html; charset=utf-8), databases (utf8mb4in MySQL). buf.toString('utf8')replaces bad bytes with�silently. Validate withisUtf8()ornew TextDecoder('utf-8', { fatal: true }).- Never decode chunks one by one: set an encoding on the stream, or use
StringDecoder,TextDecoderwith{ stream: true }, orTextDecoderStream. - Strip the UTF-8 BOM (U+FEFF) from files produced by Windows tools.
- Decode legacy encodings with
TextDecoder('windows-1252')and friends; encode them withiconv-lite. Buffer's'latin1'isn't Windows-1252. - Normalize to NFC before comparing or storing user input, compare and sort with
Intl.Collator, and use theuorvflag on regular expressions that touch non-ASCII text.