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 contain characters outside of Basic Multilingual Plane (such as most emojis), 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
*/

Difference between String.prototype .charAt vs .at