How to Get the Last Two Characters of a String in JavaScript
To get the last two characters of a string in JavaScript, call the slice()
method on the string, passing -2
as an argument. For example, str.slice(-2)
returns a new string containing the last two characters of str
.
const str = 'Coding Beauty';
const last2 = str.slice(-2);
console.log(last2); // ty
The String()
slice()
method returns the portion of a string between the start and end indexes, which are specified by the first and second arguments respectively. When only a start index is specified, it returns the entire portion of the string after this start index.
When we pass a negative number as an argument, slice()
counts backward from the last string character to find the equivalent index. So passing -2
to slice()
specifies a start index of str.length - 2
.
const str = 'Coding Beauty';
const last2 = str.slice(-2);
console.log(last2); // ty
const last2Again = str.slice(str.length - 2);
console.log(last2Again); // ty
See also
- How to Get the Last N Characters of a String in JavaScript
- How to Get the First Two Characters of a String in JavaScript
- How to Get the Last Character of a String in JavaScript
- How to Get the Substring Between Two Characters in JavaScript
- How to Get the First N Characters of a String in JavaScript
- How to get the difference between two arrays in JavaScript