Javascript get last n characters of string Example; In this tutorial you will learn how to get the last N characters from a string in javascript;
In Js we can use the slice method, substing methods to get the last characters of the original string.
Example 1:
In this example, passing a negative index of -2 means give me the last 2 characters of the string. If we pass a negative index of -3 means give me the last 3 characters of the string.
const str = 'Coding Driver';
const last2 = str.slice(-2);
console.log(last2); // er
const last3 = str.slice(-3);
console.log(last3); // ver
Example 2:
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.
const str = 'Coding Driver';
const last2 = str.slice(-2);
console.log(last2); // er
const last2Again = str.slice(str.length - 2);
console.log(last2Again); // er
Example 3:
You could also use the String.substring method to get the last N characters of a string.
//using substring
const str = 'Coding Driver';
const last2 = str.substring(str.length - 2);
console.log(last2); // er
Hope these example help you..