JS: String.prototype.charAt (get char at index) 👎

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

Return a string of single char at index.

Return empty string if index is out of bound or negative.

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

🟢 tip: better is String.prototype.at.

console.log("abc".charAt(0));
// a

console.log("abc".charAt(1));
// b
// out of bound index
console.log("abc".charAt(9) === "");

// negative index
console.log("abc".charAt(-1) === "");
/*
charAt does not work if string contains unicode character outside basic multilingual plane (e.g. emoji)

when index is pointing at a char made of a Surrogate Pair, it just return that part, which is not a character, just a unicode codepoint
*/

const xresult = "🦋".charAt(0);
console.log(xresult);
// �
console.log(xresult.toString(16));
// �
// �

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