String. prototype. charAt()
Returns the character at the given index. Outside the valid range, it returns an empty string instead of undefined.
- Returns
- A string with a single character (a UTF-16 unit), or an empty string
""when the index is out of range. - Changes the original
- No
Example
#const course = 'Python'
console.log(course.charAt(0))
console.log(course.charAt(3))
console.log(course.charAt(10) === '')
console.log(course[10])Definition and usage
#The charAt() method returns a single-character string from the given position, counted from 0. Without an argument, it returns the first character. It's one of the oldest string methods, working even in very old browsers.
It differs from square brackets in how it behaves outside the valid range: text.charAt(100) returns an empty string "", while text[100] returns undefined. Negative indexes are not supported either and also give an empty string, so at() is the tool for counting from the end.
Getting an empty string back can be convenient, since you can immediately call further methods on it, such as charAt(0).toUpperCase(), without risking an error for empty text. The method works on UTF-16 units, so with emoji it returns only half of one.
Syntax
#string.charAt()
string.charAt(index)Parameters
#index
number, optional
The character position, counted from0. Defaults to0. A value outside the range gives an empty string.
More examples
#function capitalize(text) {
return text.charAt(0).toUpperCase() + text.slice(1)
}
console.log(capitalize('exercise'))
console.log(capitalize('').length)For an empty string, text[0] would give undefined, and calling undefined.toUpperCase() would throw an error. charAt(0) returns "", so the function always works.
const fullName = 'Anna Parker'
const initials = fullName
.split(' ')
.map((part) => part.charAt(0))
.join('')
console.log(initials)Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- In new code,
text[i]orat(i)are more commonly used for single characters. ChoosecharAt()when you would rather get""thanundefinedoutside the valid range. charCodeAt()andcodePointAt()return a character's numeric code, for example to check whether it is a digit.
Related entries
#- String.prototype.at()Returns the character at the given index. Negative indexes count from the end, so at(-1) is the last character.
- String.prototype.slice()Returns a portion of a string from a start index to an end index (not included). Supports negative indexes.
- String.prototype.toUpperCase()Returns a copy of the string converted to uppercase. Handles accented letters correctly.
- String.prototype.indexOf()Returns the index of the first occurrence of the given text in a string, or -1 when it is not there.
Spotted a mistake or missing an example? Write to us.