String at

2 snippets in JavaScript

JSJavaScript

Repeat and Character Access

JS · Strings
Syntax
str.repeat(count)
str.at(index)
Example
const border = "=".repeat(30);
console.log(border);

const word = "JavaScript";
console.log(word.at(0));   // "J"
console.log(word.at(-1));  // "t"

Note at() supports negative indices to count from the end. Bracket notation str[-1] returns undefined, not the last character.

Array/String .at() Method

JS · Modern Features
Syntax
arr.at(index)
str.at(index)
Example
const stack = ["first", "second", "third", "last"];
console.log(stack.at(0));   // "first"
console.log(stack.at(-1));  // "last"
console.log(stack.at(-2));  // "third"

console.log("hello".at(-1)); // "o"

Note Works on Arrays, Strings, and TypedArrays. The main advantage over bracket notation is support for negative indices.

Frequently asked questions

How does JavaScript handle string at?
JavaScript covers this with 2 copy-ready snippets on this page. The "Repeat and Character Access" snippet in JavaScript uses `str.repeat(count)`.
Which code does the JavaScript example use?
The "Repeat and Character Access" snippet uses `str.repeat(count)`, from the Strings section of the JavaScript cheat sheet.
What other JavaScript snippets are shown for "string at"?
Besides "Repeat and Character Access", this page also shows "Array/String .at() Method".
Is there anything to watch out for?
Yes. For "Repeat and Character Access": at() supports negative indices to count from the end. Bracket notation str[-1] returns undefined, not the last character.