Get last n characters of a string in JavaScript
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:
|
1 2 3 4 5 6 7 8 |
const str = 'ECMAScript 2015'; const n = 4; console.log(str.substring(str.length - n)); /* Output: 2015 */ |
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.
|
1 2 3 4 5 6 7 8 |
const str = 'ECMAScript 2015'; const n = 4; console.log(str.slice(str.length - n)); /* Output: 2015 */ |
The following example uses slice() with negative indexes.
|
1 2 3 4 5 6 7 8 |
const str = 'ECMAScript 2015'; const n = 4; console.log(str.slice(-n)); /* Output: 2015 */ |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)