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

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2022)

str.at(index)

Extract the character at index.

  • Index can be negative, means count from right.
  • Out of bound index return undefined.

🛑 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 Index Code Unit

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

console.log("abc".at(1));
// b

console.log("abc".at(-1));
// c
// out of bound index return undefined
console.log("abcd".at(9) === undefined);
/* does not work if string contains unicode character outside basic multilingual plane (e.g. emoji) */
console.log("🦋".at(0));
// 
/*
🦋
Name: BUTTERFLY
ID 129419
HEXD 1F98B
UTF8  F0 9F A6 8B
UTF16 D83E DD8B
*/

Why String.prototype.at

String.prototype.at is a improved version of String.prototype.charAt. the new version supports negative index.

JavaScript. String, Char, Encoding, Hexadecimal

JS String.prototype