Encode and Decode Unicode Escapes in JavaScript
· One min read
JavaScript strings use UTF-16 code units. Characters in the Basic Multilingual Plane fit in one unit, while supplementary characters such as many emoji use a surrogate pair.
"A".charCodeAt(0).toString(16); // 41
"😀".codePointAt(0).toString(16); // 1f600
String.fromCodePoint(0x1f600); // 😀
Iterate by code point with for...of:
function toUnicodeEscapes(text) {
return [...text].map(char => {
const cp = char.codePointAt(0);
return cp <= 0xffff
? `\\u${cp.toString(16).padStart(4, "0")}`
: `\\u{${cp.toString(16)}}`;
}).join("");
}
Do not confuse Unicode escapes with URL encoding, HTML entities, UTF-8 bytes, or Base64; they solve different representation problems. Avoid using eval to decode external escape sequences. Parse the expected syntax explicitly and reject malformed surrogate pairs or out-of-range code points.