Get the First and Last Characters of a String in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 07 20212 min read

Get the First and Last Characters of a String #

To get the first and last characters of a string, use the charAt() method, e.g. str.charAt(0) returns the first character, whereas str.charAt(str.length - 1) returns the last character of the string.

index.js
const str = 'abcde'; const first = str.charAt(0); console.log(first); // ๐Ÿ‘‰๏ธ a const last = str.charAt(str.length - 1); console.log(last); // ๐Ÿ‘‰๏ธ e

The String.charAt method returns a new string, representing the character at the specified 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.

We subtract 1 from the string's length to get the index of the last character, because the first character has an index of 0 (and not 1).

If you pass 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); // ๐Ÿ‘‰๏ธ "" const last = str.charAt(str.length - 1); console.log(last); // ๐Ÿ‘‰๏ธ ""

There is an alternative and perhaps simpler solution.

To get the first and last characters of a string, access the string at the first and last indexes. For example, str[0] returns the first character, whereas str[str.length - 1] returns the last character of the string.

index.js
const str = 'abcde'; const first = str[0]; console.log(first); // ๐Ÿ‘‰๏ธ a const last = str[str.length - 1]; console.log(last); // ๐Ÿ‘‰๏ธ e

If we just 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 const last = str[str.length - 1]; console.log(last); // ๐Ÿ‘‰๏ธ 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.

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