Get the last N characters of a String in Javascript

Javascript get last N characters of string Example; In this tutorial you will learn how to get last N character from a string in Javascript;

In Js we can use str.slice and substring methods to get last n character from string see the below example;

Example 1:

To get the last N characters of a string you just need to call the slice method on the string and pass in -n as a parameter. Its returns a new string containing the last 3 characters of the original string.

const str = 'Coding Driver';

const last2 = str.slice(-2); // er
console.log(last2);

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

Example 2:

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

const str = 'Coding Driver';

const last2 = str.slice(str.length - 2); // er
console.log(last2);

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

Example 3:

You can also use the String.substring method to get the last N characters of a string.

const str = 'Coding Driver';

const last2 = str.substring(str.length - 2); // er
console.log(last2);

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