Get the last N characters of a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 17, 2022

banner

Photo from Unsplash

Get the last N characters of a String #

To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str.slice(-3) returns a new string containing the last 3 characters of the original string.

index.js
const str = 'Hello World'; const last3 = str.slice(-3); // 👉️ rld console.log(last3); const last2 = str.slice(-2); // 👉️ ld console.log(last2);

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

For example, passing a negative index of -3 means give me the last 3 characters of the string.

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

index.js
const str = 'Hello World'; const last3 = str.slice(-3); // 👉️ rld console.log(last3); const last3Again = str.slice(str.length - 3); // 👉️ rld console.log(last3Again);

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

Even if we try to get more characters than the string contains, String.slice won't throw an error. Instead, it will return a copy of the entire string.

index.js
const str = 'Hello World'; const last100 = str.slice(-100); // 👉️ Hello World console.log(last100);

In the example, we tried to get the last 100 characters of a string that only contains 11 characters.

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 N characters of a string.

index.js
const str = 'Hello World'; // 👇️ using substring const last3 = str.substring(str.length - 3); // 👉️ rld console.log(last3);

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 quite confusing.

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

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.