JS: String.prototype.charAt (Extract Char at Index) ❌

By Xah Lee. Date: . Last updated: .

🟢 TIP: better is String.prototype.at.

str.charAt(index)

Extract the character at index.

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

🛑 WARNING: string methods do not work the way you think if it contains characters outside of Unicode Basic Multilingual Plane (e.g. emoji 🦋.). See JS: String Code Unit

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) */
console.log("🦋".charAt(0));
// 
/*
🦋
Name: BUTTERFLY
ID 129419
HEXD 1F98B
UTF8  F0 9F A6 8B
UTF16 D83E DD8B
*/

JavaScript. String, Char, Encoding, Hexadecimal

JS String.prototype