How to get last character of a string in JavaScript
In this tutorial, we will learn two different ways to get the last character of a string in JavaScript.
In JavaScript, strings are the sequence of characters, where the index of the first character is 0
, the second character is 1
, third character is 3
and last character index is string.length-1 etc.
1. Using charAt() method
To get the last character of a string in JavaScript, we can use the built-in charAt()
method by passing string.length-1
as an argument to it.
The string.length-1
returns the index of a last character.
Here is an example:
const str = "hello";
const lastCharacter = str.charAt(str.length-1);
console.log(lastCharacter); // "o"
2. Using slice() method
If we pass -1
as an argument to the slice()
method we can get the last character of a string.
const string = "hello";
const lastCharacter = string.slice(-1);
console.log(lastCharacter); // "o"
Note: Negative index -1 is same as string.length-1
.