Get the Last 2 Characters of a String in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 24 20212 min read

banner

Photo by Aziz Acharki

Get the Last 2 Characters of a String #

To get the last two characters of a string, call the slice() method, passing it -2 as a parameter. The slice method will return a new string containing the last two characters of the original string.

index.js
const str = 'hello world'; const last2 = str.slice(-2); console.log(last2); // ๐Ÿ‘‰๏ธ ld

The parameter we passed to the String.slice method is the start index.

The start index is the index at which the method starts extracting characters from the string.

Passing a negative index of -2 means - give me the last 2 characters of the string.

This is the same as passing string.length - 2 as the start index.

index.js
const str = 'hello world'; const last2 = str.slice(-2); console.log(last2); // ๐Ÿ‘‰๏ธ ld const last2Again = str.slice(str.length - 2); console.log(last2Again); // ๐Ÿ‘‰๏ธ ld

In both examples, we tell the slice method to copy the last 2 characters of the string into a new string.

The slice method does not change the original string, it returns a new string. Strings are immutable in JavaScript.

Even if we try to get more characters than the string contains, String.slice won't throw an error, instead it returns a new string containing all characters.

index.js
const str = 'h'; const last2 = str.slice(-2); console.log(last2); // ๐Ÿ‘‰๏ธ h

In this example, we tried to get the last 2 characters of a string that only contains 1 character.

As a result the slice method returned a copy of the entire string.

You could also use the String.substring method to get the last two characters of a string.

index.js
const str = 'one two'; const last2 = str.substring(str.length - 2); // ๐Ÿ‘‰๏ธ wo console.log(last2);

However, using the String.slice method is more intuitive and readable.

For example, if you pass a negative argument to the String.substring method, it treats it as if you passed 0, which is very confusing.

For other differences between String.substring and String.slice, check out the MDN docs.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee