JavaScript Reference ยท String
String.fromCharCode()
Reference for JavaScript String.fromCharCode(): build a string from UTF-16 code unit numbers, how large values wrap, and why emoji need surrogate pairs.
String.fromCharCode() is a static method that builds a string from one or more numbers, each treated as a UTF-16 code unit. It is the inverse of charCodeAt(): where "A".charCodeAt(0) gives 65, String.fromCharCode(65) gives "A".
A code unit is a 16-bit value, so the method can directly produce characters up to U+FFFF. Characters beyond that, such as most emoji, need two code units (a surrogate pair). For those, String.fromCodePoint() is usually the better tool.
String.fromCharCode(72, 105); // "Hi"
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
String.fromCharCode() String.fromCharCode(num1) String.fromCharCode(num1, num2, /* โฆ, */ numN)
| Name | Description |
|---|---|
num1, โฆ, numN |
Numbers from 0 to 65535, each a UTF-16 code unit. Each is converted to a number and then reduced modulo 65536 (so only the lowest 16 bits count). Fractions are truncated and NaN becomes 0. |
Return value: a string with one code unit per argument, in order. With no arguments it returns an empty string.
Exceptions: none for ordinary numbers. A Symbol or BigInt argument throws a TypeError.
Usage notes
- It is static. Call it on
String, not on a string value:"abc".fromCharCode(65)is aTypeError. - 16 bits only.
String.fromCharCode(0x1f600)does not give the grinning-face emoji; the value is cut down to its lower 16 bits, which is a different character. UseString.fromCodePoint()for any code point, or pass the surrogate pair explicitly. - Lone surrogates are allowed. The result may contain unpaired surrogates (
0xD800to0xDFFF), which form a string that is not well formed and cannot be encoded as valid UTF-8.isWellFormed()can test for this. - Spread, not array. Passing an array directly does not work, since it becomes one argument; use
String.fromCharCode(...codes)orapply. For huge arrays, spread can exceed the engine's argument limit, so convert in chunks. - Character codes are not letters for every language. A "character" a user sees can consist of several code units or code points; counting and slicing by code unit can split it.
- Prefer readable literals when you know the character:
"รฉ"or"รฉ"is clearer thanString.fromCharCode(233). - Common uses: generating letters from numbers, simple ciphers, decoding arrays of bytes in Latin-1 form (each byte as one code unit), and building test data.
Browser support
String.fromCharCode() is a classic method that works in every browser and Node.js version.