codePointAt Reads Full Emoji Code Points

codePointAt reads full Unicode code points even for emoji that occupy two UTF-16 units, and fromCodePoint turns numeric points back into strings.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
// emoji 占两个 UTF-16 码元:length 数的是码元,codePointAt 读的是完整码点
const emoji = String.fromCodePoint(0x1F600);
console.log('units      :', emoji.length);
console.log('codepoint  :', emoji.codePointAt(0).toString(16));

// charCodeAt 只能看到半个代理项,codePointAt 才能拼回完整码点
console.log('charCodeAt :', emoji.charCodeAt(0).toString(16));

// fromCodePoint 与 codePointAt 互为往返
const restored = String.fromCodePoint(emoji.codePointAt(0));
console.log('roundtrip  :', restored === emoji);

// 普通字符一个码元一个码点
console.log('ascii      :', 'a'.codePointAt(0));

// 用码点遍历:for...of 按码点走,不按码元走
const text = emoji + 'x' + emoji;
console.log('iter count :', [...text].length, 'units:', text.length);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

units      : 2
codepoint  : 1f600
charCodeAt : d83d
roundtrip  : true
ascii      : 97
iter count : 3 units: 5

How the snippet works

The demo data lives in module-level bindings: emoji, restored, text.

Applying it

The demo output is labeled (units :, codepoint :, charCodeAt :), so every printed line maps back to its originating operation.

Statements that matter

const restored = String.fromCodePoint(emoji.codePointAt(0));
const emoji = String.fromCodePoint(0x1F600);
const text = emoji + 'x' + emoji;

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. Its state lives in module-level bindings: `emoji`, `restored`, `text`.