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

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

get the character at index. Return a string of single char.

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

🛑 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

🟢 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) */
console.log("🦋".charAt(0));
// �

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