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
undefinedwhen the index falls outside the string. - Changes the original
- No
Example
#const word = 'Cosmos'
console.log(word.at(0))
console.log(word.at(-1))
console.log(word.at(-2))
console.log(word.at(10))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
#string.at(index)Parameters
#index
number
The character's position.0is the first character, and negative values count from the end (-1is the last).
More examples
#const code = 'CSS'
console.log(code.at(-1))
console.log(code[-1])
console.log(code[code.length - 1])
console.log(code.charAt(-1) === '')function ensureDot(sentence) {
return sentence.at(-1) === '.' ? sentence : sentence + '.'
}
console.log(ensureDot('Lesson complete'))
console.log(ensureDot('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, useslice(-3).text[-1]does not count from the end, it looks for a property named "-1", so it returnsundefined. Always useat()for negative indexes.
Related entries
#- String.prototype.charAt()Returns the character at the given index. Outside the valid range, it returns an empty string instead of undefined.
- String.prototype.slice()Returns a portion of a string from a start index to an end index (not included). Supports negative indexes.
- String.prototype.lengthThe length of a string, i.e. the number of UTF-16 code units. The property is read-only.
- Array.prototype.at()Returns the element at the given index, which can also be counted from the end.
Spotted a mistake or missing an example? Write to us.