How to get the Last Character of a String in JavaScript
Table of Contents
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.
JAVASCRIPTconst string = "Hello World";
const lastCharacterIndex = string.length - 1;
const lastCharacter = string.charAt(lastCharacterIndex);
console.log(lastCharacter);
BASHd
More concisely, we can also do this:
JAVASCRIPTconst string = "Hello World";
const lastCharacter = string.charAt(string.length - 1);
console.log(lastCharacter);
BASHd
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.
JAVASCRIPTconst string = "Hello World";
const lastCharacter = string.slice(-1);
console.log(lastCharacter);
BASHd
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.
JAVASCRIPTconst string = "Hello World";
const lastCharacter = string[string.length - 1];
console.log(lastCharacter);
BASHd
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!
- Getting Started with Express
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- How to build a Discord bot using TypeScript
- Getting Started with Deno
- How to deploy an Express app using Docker
- Getting Started with Sass
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase