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

Tip

If we try to get more characters than the string contains, slice() returns the entire string instead of throwing an error.

const str = 'Coding Beauty';

const last50 = str.slice(-50);
console.log(last50); // Coding Beauty

In this example, we tried to get the last 50 characters of the string by passing -50 as the first argument, but the string 'Coding Beauty' contains only 13 characters. Hence, we get the entire string from slice().

Note

We can use substring() in place of slice() to get the first two characters of a string:

const str = 'Coding Beauty';

const last3 = str.substring(str.length - 3);
console.log(last3); // uty

However, we have to manually calculate the start index ourselves with str.length - 2, which makes the code less readable. This is because unlike slice(), substring() uses 0 as the start index if we pass a negative number.

const str = 'Coding Beauty';

// -2 is negative, uses 0 instead
const notLast2 = str.substring(-2);

console.log(notLast2); // Coding Beauty


11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.


Leave a Comment

Your email address will not be published. Required fields are marked *