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

To get the last N characters of a string in JavaScript, call the slice() method on the string, passing -N as an argument. For example, str.slice(-3) returns a new string containing the last 3 characters of str.

const str = 'Coding Beauty';

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

const last6 = str.slice(-6);
console.log(last6); // Beauty

const last10 = str.slice(-10);
console.log(last10); // ing Beauty

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 we only specify a start index, 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 -N to slice() specifies a start index of str.length - N.

const str = 'Coding Beauty';

const last6 = str.slice(-6);
console.log(last6); // Beauty

const last6Again = str.slice(str.length - 6);
console.log(last6Again); // Beauty

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 N 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 - N, which makes the code less readable. This is because unlike slice(), substring() uses 0 as the start index if a negative number is passed.

const str = 'Coding Beauty';

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

console.log(notLast3); // 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 *