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 TypeScript
- How to Install Node on Windows, macOS and Linux
- Getting Started with Electron
- How to deploy a .NET app using Docker
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- Getting Started with Handlebars.js
- Creating a Twitter bot with Node.js
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript