The charAt
method is accepted by strings in JavaScript, returning the position of the character passed as a parameter within the string.
If the string contains multiple occurrences of the character passed as a parameter, the charAt
method will return only the position of the first occurrence. If the character is not present in the string, the charAt
method shall return an empty string.
The charAt
method can be used with String objects, although it will also work with standard strings defined with single or double quotes, as well as with literal templates.
In this example we use the charAt
method on a standard string, getting first the character at position 0, then the character at position 2 and finally the character at position 20, which is an index that does not exist in the string:
const Zerocharacter = 'JavaScript'.charAt
(0) // 'J' const Twocharacter = 'JavaScript'.charAt
(2) // 'v' const Twentycharacter = 'JavaScript'.charAt
(20) // ""
The charAt
method works in the same way with String
objects, as we see in the following example
const chain = new String('JavaScript');
const character = chain.charAt
(0); // 'J'
The charAt
method is case sensitive, so the J character is not the same as the j character.
Read also: Strings in JavaScript: What they are and how to use them