String.prototype.codePointAt()
codePointAt(index) Returns:
number | undefined · Added in vES2015 · Updated March 13, 2026 · String Methods string unicode code-point encoding
The codePointAt method returns a non-negative integer representing the Unicode code point at the given index. Unlike charCodeAt, it correctly handles surrogate pairs—characters outside the Basic Multilingual Plane (BMP) that require two 16-bit units in JavaScript strings.
Syntax
codePointAt(index)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| index | number | — | The position in the string. Returns undefined if index is out of bounds or negative. |
Examples
Basic usage
const str = "Hello, 🌍";
console.log(str.codePointAt(0)); // 72 (H)
console.log(str.codePointAt(1)); // 101 (e)
console.log(str.codePointAt(5)); // 32 (space)
console.log(str.codePointAt(7)); // 128751 (🌍)
Handling surrogate pairs
const emoji = "😀";
console.log(emoji.codePointAt(0)); // 128512
console.log(emoji.charCodeAt(0)); // 55357 (incorrect - returns high surrogate)
// Spread operator (iterates by code points)
[..."A😀Z"].forEach(cp => console.log(cp.codePointAt(0)));
// 65
// 128512
// 90
Converting code points back to characters
const codePoint = 128512; // 😀
console.log(String.fromCodePoint(codePoint)); // 😀
// Process each code point
const str = "Hello 🌍";
const codePoints = [...str].map(char => char.codePointAt(0));
console.log(codePoints); // [72, 101, 108, 108, 111, 32, 128751]
Common Patterns
Iterate over code points safely
function getCodePoints(str) {
return [...str].map(char => char.codePointAt(0));
}
console.log(getCodePoints("abc")); // [97, 98, 99]
console.log(getCodePoints("a🌀c")); // [97, 128300, 99]
Check if a string contains surrogate pairs
function hasSurrogates(str) {
return [...str].some(char => char.codePointAt(0) > 0xFFFF);
}
console.log(hasSurrogates("hello")); // false
console.log(hasSurrogates("hello😀")); // true
Compare with charCodeAt
const str = "A🎉";
console.log(str.charCodeAt(1)); // 55349 (high surrogate)
console.log(str.codePointAt(1)); // 128397 (correct 🎉)
// charCodeAt treats each 16-bit unit separately
// codePointAt treats the string as code points
Process text containing emojis
function reverseString(str) {
return [...str].reverse().join("");
}
console.log(reverseString("Hello😀World")); // dlroW😀olleH
// Without spreading, reversing would break the emoji:
// "Hello😀World".split("").reverse().join("") // "dlroW口olleH" (broken)
See Also
- string::charAt — Returns the character code at an index (does not handle surrogates)
- string::codePointAt — Returns the code point at an index (handles surrogates)
- string::fromCodePoint — Creates a string from code point values