How To Get The Last N Characters Of A String In JavaScript

Get the last n characters of a string in javascript

In this tutorial, we will show you how to get the last n characters of a string in JavaScript. This is a common problem that many of us have to deal with while learning or working with JavaScript strings. There are many ways to get it done, but we will demonstrate the two common ones.

Get the last n characters of a string in JavaScript  

Method 1: Using a for loop

We will start with the most basic method. You might be familiar with using a for loop to scan through all the elements of a string or from the first element to a specific element. Here, I will show you how to adjust it a little bit so that we can get the last n characters of the string. 

First, to use a for loop, we have to know the start point and the endpoint. Let’s say we have myStr as our string.

For example, if myStr has 5 characters and we want to get the last 3 characters, we will have to run from the third character to the last. So our start point is calculated like this:  myStr.length - n + 1. However, the string in JavaScript starts from 0, so we don’t have to plus 1. Therefore:  

Start point:  myStr.length - n

End point: myStr.length 

Let’s apply it to a small program: 

var myStr = 'Welcome to LearnShareIt.com';
var n = 3;
var result ='';

for (let i = (myStr.length - n); i < myStr.length; i++) {
  result += myStr[i];
};

console.log(result);

Output: 

com

Method 2: Using string.slice()

Now let’s move on to an extremely short and fast way to get the last characters of the string. JavaScript has supported us with the string.slice() methods to work with strings. The string.slice() method will extract a part in our string and return it to a new string. 

Syntax:

string.slice(start, end)

Parameters:

  • start: the start point
  • end (optional): the end point

Example: 

var myStr = 'Welcome to LearnShareIt.com';
var n = 3;
var result ='';

result = myStr.slice(n);

console.log(result);

Output:

come to LearnShareIt.com 

We can use the slice() method to get the last n characters by using myStr.slice(-n) instead of myStr.slice(n).

Completed code: 

var myStr = 'Welcome to LearnShareIt.com';
var n = 3;
var result ='';

result = myStr.slice(-n);

console.log(result);

Output: 

com

Summary

We have guided you through two common methods to get the last n characters of a string in JavaScript. This is an important skill that we should know when working with strings. The two ideas are quite simple: using a for loop and string.slice() method.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *