This post will discuss how to get the last n characters of a string in JavaScript.

There are several methods to get the last n characters from a string using JavaScript native methods substring() and slice().

1. Using String.prototype.substring() function

The substring() method returns the part of the string between the start and end indexes, or at the end of the string. Following is a simple example demonstrating the usage of substring() to get the last n characters from the string:

Download  Run Code

2. Using String.prototype.slice() function

Another plausible way to get the last n characters from the string is using the slice() method. The slice() method extracts a section of string and returns it as a new string.

Download  Run Code

 
The following example uses slice() with negative indexes.

Download  Run Code

 
You can also use the substr() method in a similar manner, but it is considered a legacy function and may be removed in the future.

That’s all about getting the last n characters of a string in JavaScript.