JavaScriptStrings

String.prototype.at()

Returns the character at the given index. Negative indexes count from the end, so at(-1) is the last character.

Returns
A string with a single character (a UTF-16 unit), or undefined when the index falls outside the string.
Changes the original
No
On this page

Example

#
JavaScript
const word = 'Cosmos'

console.log(word.at(0))
console.log(word.at(-1))
console.log(word.at(-2))
console.log(word.at(10))
Console
C
s
o
undefined

Definition and usage

#

The at() method returns a single-character string from the given position. For positive indexes it works like square brackets, but it also understands negative indexes: -1 is the last character, -2 the second to last, and so on.

That means text.at(-1) is all you need instead of text[text.length - 1]. When the index falls outside the string, the method returns undefined. Fractions are truncated toward zero.

Like other index-based methods, at() works on UTF-16 units. For emoji that take up two units, it returns only half the character, so [...text].at(-1) is the better choice in that case.

Syntax

#
Syntax
string.at(index)

Parameters

#
  • index

    number

    The character's position. 0 is the first character, and negative values count from the end (-1 is the last).

More examples

#
Comparison with brackets and charAt()
JavaScript
const code = 'CSS'

console.log(code.at(-1))
console.log(code[-1])
console.log(code[code.length - 1])
console.log(code.charAt(-1) === '')
Console
S
undefined
S
true
Checking the last character
JavaScript
function ensureDot(sentence) {
  return sentence.at(-1) === '.' ? sentence : sentence + '.'
}

console.log(ensureDot('Lesson complete'))
console.log(ensureDot('Module passed.'))
Console
Lesson complete.
Module passed.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • at() returns a single character. To grab the last few characters, use slice(-3).
  • text[-1] does not count from the end, it looks for a property named "-1", so it returns undefined. Always use at() for negative indexes.

Related entries

#

Spotted a mistake or missing an example? Write to us.