How to Get the Last Two Characters of a String in JavaScript

Last updated on June 24, 2022
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

Every Crazy Thing JavaScript Does

Every Crazy Thing JavaScript Does
Avoid painful bugs and save valuable time with Every Crazy Thing JavaScript Does, a captivating guide to the subtle caveats and lesser-known parts of JavaScript.

See also