How to Get the Last Character of a String in JavaScript

It’s pretty straightforward to get the last character from a string in JavaScript. You’ll usually need this operation to parse and manipulate textual data. We’ll cover how to do this below.

Understanding String Indexing

In JavaScript, strings are indexed from 0 to length - 1, where length is the number of characters in the string. This indexing allows you to access each character using square brackets [].

Accessing the Last Character

You can get the last character by subtracting one from the string's length property and using this value as the index.

let str = "Hello"; let lastChar = str[str.length - 1]; console.log(lastChar); // Outputs: o

Using charAt Method

The charAt() method returns the character at a specified index. For the last character, pass string.length - 1 as the argument.

let str = "Hello"; let lastChar = str.charAt(str.length - 1); console.log(lastChar); // Outputs: o

Slice Method

The slice() method can extract a section of a string. To get the last character, use -1 as the start slice index.

let str = "Hello"; let lastChar = str.slice(-1); console.log(lastChar); // Outputs: o

Using Regular Expressions

Regular expressions can match patterns within strings. To find the last character, use a regex pattern.

let str = "Hello"; let lastChar = str.match(/.$/)[0]; console.log(lastChar); // Outputs: o

Handling Edge Cases

It's good practice to check if the string is empty before trying to access its characters to avoid errors.

let str = ""; let lastChar = str.length > 0 ? str[str.length - 1] : ''; console.log(lastChar); // Outputs: Empty string

Performance Considerations

For performance-critical applications, direct indexing or charAt() are preferred methods due to their simplicity and speed.

Remember to handle strings with care, as attempting to access an index that doesn't exist will return undefined, not an error. Always ensure that the string is not empty to avoid such issues.

Invite only

We're building the next generation of data visualization.