Get the last N characters of a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 05 20212 min read

banner

Photo by John Gibbons

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 parameter 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 returns a new string containing all characters.

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

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

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