Borislav Hadzhiev
Fri Nov 05 2021·2 min read
Photo by Ben White
Use the charAt()
method to get the nth character in a string, e.g.
str.charAt(1)
gets the second character in the string. The only parameter the
charAt
method takes is the index of the character to be returned. If the index
does not exist in the string, an empty string is returned.
const str = 'one two'; // ✅ Using charAt console.log(str.charAt(1)); // 👉️ "n" console.log(str.charAt(2)); // 👉️ "e" // 👇️ Count backwards console.log(str.charAt(str.length - 1)); // 👉️ "o"
The
String.charAt
method takes an integer between 0
and string.length - 1
and returns the
corresponding character.
0
, and the index of the last - string.length - 1
.When passed an index out of bounds, the charAt()
method returns an empty
string.
console.log(''.charAt(5)); // 👉️ ""
You can count backwards, by subtracting the number of characters from the
string's length. For example, string.length - 2
gives us the second to last
character in the string.
const str = 'one two'; console.log(str.charAt(str.length - 2)); // 👉️ "w"
An alternative approach is to use bracket notation.
Use bracket notation to get the nth character in a string, e.g. str[0]
returns the first character in the string. When provided an index that does not
exist in the string, you get an undefined
value back.
const str = 'one two'; // ✅ Using bracket notation console.log(str[1]); // 👉️ "n" console.log(str[2]); // 👉️ "e" // 👇️ Count backwards console.log(str[str.length - 1]); // 👉️ "o"
[]
notation being used to access a string at a specific index.The bracket notation approach differs from the charAt
method in that, it
returns undefined
when provided an index that does not exist in the string.
console.log(''[5]); // 👉️ undefined
You can also use bracket notation to count backwards, simply subtract the number of characters from the string's length.
const str = 'one two'; console.log(str[str.length - 2]); // 👉️ "w"