JS: String.prototype.at (get char at index) β­•

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2022)

str.at(index)

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

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

πŸ›‘ 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("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
*/

String.prototype .charAt vs .at