In this tutorial you will learn how to get the Last Characters of a String in JavaScript;
In Javascript to get the last character of a string, you can use the charAt() and slice() method.
1. Using charAt() Method
Indexes are zero-based in JavaScript. The first character in the string has an index of 0, so the last character in the string has an index of str.length – 1.
const str = 'hello';
const last = str.charAt(str.length - 1);
console.log(last); // o
let n = 2
const lst2 = str.slice(-n);
console.log(lst2); // 'lo'
If passed an index that doesn’t exist, the charAt() method returns an empty string.
const str = '';
const last = str.charAt(str.length - 1);
console.log(last); // ""
2. Using slice() Method
In Js you can use the String.slice() method to get the last character of a string. When passed an index of -1, the slice() method returns the last character of the string.
const str = 'hello';
const last = str.slice(-1);
console.log(last); // 'o'
const last2 = str.slice(-2);
console.log(last2); // 'lo'
const last3 = str.slice(-3);
console.log(last3); // 'llo'
The slice()
method returns an empty string if the specified index is not found in the string.
const str = '';
const last = str.slice(-1);
console.log(last); // ''
3. Using bracket notation
To get the last character of a string, use bracket notation to access the string at the last index. Indexes are zero-based, so the index of the last character in the string is str.length – 1.
const str = 'hello';
const last = str[str.length - 1];
console.log(last); // o