JS: String.prototype.charCodeAt (char to id) 👎

By Xah Lee. Date: . Last updated: .
str.charCodeAt(index)

Return the CHAR ID at index. (technically, return a integer that's the String Code Unit at index index in str.)

console.log("abc".charCodeAt(0));
// 97

console.log("abc".charCodeAt(1));
// 98

🛑 warning: if string contains emoji (🦋) or rarely used unicode character, result of string methods may not be what you expect. See JS: String Index and Code Unit

console.log("🦋".charCodeAt(0));
// 55358

console.log("🦋".charCodeAt(0).toString(16));
// d83e

// d83e is the first part of surrogate pair in utf 16 encoding for the butterfly char

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

// get the second part of surrogate pair
console.log("🦋".charCodeAt(1).toString(16));
// dd8b