Get last n characters of string
How to solve it
For this task, I recommend using again the slice method.
With the
slice
method, you can extract a part of a string without modifying the original string. You call it with two parameters (startIndex and endIndex). startIndex defines the index of the first character in the string that you want to extract. endIndex defines the first character that you do not want to extract. console.log('wxyz'.slice(1,3));
// output: 'xy'
You can omit the endIndex parameter. Then,
slice
will simply return all characters beginning at startIndex. console.log('wxyz'.slice(1));
// output: 'xyz'
It is important to know, that you can call
slice
with a negative startIndex. In this case, startIndex is not an index but identifies the starting position by counting backwards from the end of the string. // get last two characters of string:
console.log('wxyz'.slice(-2);
// output: 'xy'
This is all you need to solve this task.