Open In App

How to Get the Last N Characters of a String in JavaScript

Last Updated : 31 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to get the last N characters of a string in JavaScript. We have given a string and we need to get the “n” character from the last of the string. There are various methods for finding the “n” character from the last of the string.

Below are the following methods through which we get the last N characters of a string in JavaScript:

  • Using substring() Method
  • Using slice() Method
  • Using loop and string concatenation

Approach 1: Using substring() Method in JavaScript

In this approach, we will use the substring() method for removing the last n character of the string. The string.substring() is an inbuilt function in JavaScript that is used to return the part of the given string from the start index to the end index. Indexing starts from zero (0). By calculating the starting index as “str.length - n", we get the last n character.

Syntax: 

string.substring( Startindex, Endindex )

Example:

Javascript




function getLastCharacter(str,n) {
    let newString = str.substring(str.length - n);
    return newString;
  
}
let str = "Geeksforgeeks";
let n=5;
console.log(getLastCharacter(str,n));


Output

geeks

Approach 2: Using slice() Method in JavaScript

In this approach, we will use the slice method for removing the last n character of the string. The string.slice() is an inbuilt method in javascript that is used to return a part or slice of the given input string.

Syntax:

string.slice( startingIndex, endingIndex )

Example:

Javascript




function getCharacter(str,n) {
    let newString = str.slice(-n);
    return newString;
  
}
let str = "Hello Geeks!";
let n=6
console.log(getCharacter(str,n));


Output

Geeks!

Approach 3: Using loop and string concatenation

In this approach, we will use for loop to iterate over the string but in this we iterate from the index str.length-n to the end. So that we can get the last n character of a string.

Example:

Javascript




function getCharacter(str, n) {
    let newString = '';
    for (let i = str.length - n; i < str.length; i++) {
        newString += str[i];
    }
    return newString;
  
}
let str = "Hello Geeks!";
let n = 6
console.log(getCharacter(str, n));


Output

Geeks!


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads