JS: String.fromCharCode (ID to Char) 👎

By Xah Lee. Date: . Last updated: .
String.fromCharCode(char_id_1, char_id_2, etc)

Turn each Char ID into a character and join them. char_id is a integer.

return a string.

🛑 warning: If char_id ≥ 65536, then a value of modulo(char_id, 2^16) is used.

🟢 tip: better is String.fromCodePoint

🛑 warning: if string contains a character outside of Basic Multilingual Plane (such as most emoji 🦋 or rarely used Chinese character), result of string methods may be unexpected. See JS: String Index and Code Unit.

/* convert sequence of unicode codepoint to string. */
console.assert(
 String.fromCharCode(97, 98) === "ab",
);

// character: a (codepoint 97, #o141, #x61)
// character: b (codepoint 98, #o142, #x62)
// String.fromCharCode() does not work for emoji or other rare unicode char

// try to generate the butterfly 🦋 char
console.log(String.fromCharCode(129419));
// 曆

// result is not what we want

/*
🦋
Name: BUTTERFLY
Codepoint: 129419
HEXD: 1F98B
UTF8: F0 9F A6 8B
UTF16: D83E DD8B
*/