Get the first Character of a String in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 22 20212 min read

Get the first Character of a String #

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.

index.js
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.

Indexes are zero-based in JavaScript. The first character in the string has an index of 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.

index.js
const str = ''; const first = str.charAt(0); console.log(first); // ๐Ÿ‘‰๏ธ ""

An alternative approach is to directly access the index.

Get the first Character of a String directly #

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.

index.js
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.

index.js
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.

It's better to know that even if you try to access an index that doesn't exist in the string, you would get a string back, instead of undefined.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee