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. Index can be negative, means count from right.

  • Return a string of single char.
  • Return undefined if index is out of bound.

πŸ›‘ 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.

console.assert(
 "abc".at(0) === "a",
);

console.assert(
 "abc".at(1) === "b",
);

console.assert(
 "abc".at(-1) === "c",
);
// out of bound index return undefined
console.assert(
 "".at(0) === undefined,
);
/* does not work if string contains unicode character outside basic multilingual plane (e.g. emoji) */
console.log("πŸ¦‹".at(0));
// οΏ½

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

String.prototype .charAt vs .at