Borislav Hadzhiev
Fri Oct 22 2021·2 min read
Photo by Ganesh Ravikumar
To get the first character of a string, call the charAt()
method on the
string, passing it 0
as a parameter - str.charAt(0)
. The method returns a
new string containing the character at the specified index.
const str = 'abcd'; const first = str.charAt(0); console.log(first); // 👉️ a
The String.charAt method returns a new string that contains the character at the passed in index.
0
and the last has an index of str.length - 1
.If you supply an index that doesn't exist in the string, the charAt
method
returns an empty string.
const str = ''; const first = str.charAt(0); console.log(first); // 👉️ ""
An alternative approach is to directly access the index.
To get the first character of a string, access the string at index 0
, using
bracket notation. For example, str[0]
returns the first character of the
string.
const str = 'abcd'; const first = str[0]; console.log(first); // 👉️ a
If we access the string at the specific index, we can avoid calling the charAt
method.
However, if you try to access the string at an index that doesn't exist you get
undefined
back.
const str = ''; const first = str[0]; console.log(first); // 👉️ undefined
This is the reason I prefer the charAt
method over directly accessing the
index of the string.
undefined
.