How to get the Last Character of a String in JavaScript

Updated onbyAlan Morel
How to get the Last Character of a String in JavaScript

Strings in JavaScript essentially function as arrays of characters.

When you're working with strings, you might want to be able to get the last character of it.

In this post, we'll learn the different ways you can get the last character of a string in JavaScript.

Using the charAt() Method

An easy way to get the last character is to use the charAt() method.

This method accepts an index and will return the character at that index.

All we need to do is pass in the index of the last character we want to get.

JAVASCRIPT
const string = "Hello World"; const lastCharacterIndex = string.length - 1; const lastCharacter = string.charAt(lastCharacterIndex); console.log(lastCharacter);
BASH
d

More concisely, we can also do this:

JAVASCRIPT
const string = "Hello World"; const lastCharacter = string.charAt(string.length - 1); console.log(lastCharacter);
BASH
d

Using the slice() Method

We can also use the slice() method to get the last character of a string.

Since slice takes a string and returns a substring, we can pass in the string and start the slicing at -1, which will return the last character of the string.

JAVASCRIPT
const string = "Hello World"; const lastCharacter = string.slice(-1); console.log(lastCharacter);
BASH
d

This works because when you provide slice a negative number, it will start at the end of the string and work its way backwards.

Using the bracket notation

The final way you can get the last character of a string is to use the bracket notation.

Remember, because a string can be thought of as an array of characters, we can use the bracket notation to get the last character of a string by passing in the index of the last character.

JAVASCRIPT
const string = "Hello World"; const lastCharacter = string[string.length - 1]; console.log(lastCharacter);
BASH
d

Conclusion

In this post, we looked at the three different ways you can get the last character of a string in JavaScript.

Simply put, you can either use the charAt() method, the slice() method, or the bracket notation on a string to get the last character of it.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.