Get the First and Last Characters of a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 7, 2021

banner

Photo from Unsplash

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.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.