JS: String.prototype.codePointAt (Char to ID)

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

str.codePointAt(index)
  • Return a integer that's the Code Point of character at position index of str, but if index is at the beginning of a Surrogate Pair, return the code point of the whole char, not just the first part.
  • Return undefined when out of bound.
// character: a (codepoint 97, #x61)
console.assert(
 "abc".codePointAt(0) === 97,
);

// character: b (codepoint 98, #x62)
console.assert(
 "abc".codePointAt(1) === 98,
);

// character: α (codepoint 945, #x3b1)
console.assert(
 "α".codePointAt(0) === 945,
);

// s------------------------------

// return undefined when out of bound
console.assert(
 "".codePointAt(0) === undefined,
);

🛑 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.

/* the butterfly character, its codepoint in hexadecimal is
1F98B

in utf16 encoding, it is a Surrogate Pair, meaning, it's 2 16bits unit:
D83E DD8B
*/

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

// get the codepoint
console.assert(
 "🦋".codePointAt(0) === 129419,
);

// get the codepoint in hexadecimal
console.assert(
 "🦋".codePointAt(0).toString(16) === "1f98b",
);

/*
the value 1f98b is the codepoint of the butterfly char.
*/

// if index is at the second part of surrogate pair, it returns the second part of Surrogate Pair

console.assert(
 "🦋".codePointAt(1) === 56715,
);

console.assert(
 "🦋".codePointAt(1).toString(16) === "dd8b",
);
// codePointAt does not work well if you have emoji or rare unicode in string

// we want to get code point of b
// The character b codepoint is 98.
console.log("🦋b".codePointAt(1));
// 56715

// wrong.

// 56715 in hexadecimal it is
console.log("🦋b".codePointAt(1).toString(16));
// dd8b

/*
dd8b is second half of the butterfly in UTF16.
*/

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

See also: Unicode Search 🔍