How to usesubstring() Method in JavaScript 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 = "w3wiki";
let n=5;
console.log(getLastCharacter(str,n)); 

Output
geeks

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

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:

Table of Content

  • Approach 1: Using substring() Method in JavaScript
  • Approach 2: Using slice() Method in JavaScript
  • Approach 3: Using loop and string concatenation
  • Approach 4: Using String’s substr() Method
  • Approach 5: Using Array.from() and slice() Method

Similar Reads

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....

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....

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....

Approach 4: Using String’s substr() Method

The substr() method is used to extract parts of a string, beginning at the specified start position, and returns the specified number of characters starting from that position to the end of the string....

Approach 5: Using Array.from() and slice() Method

In this approach, we will use the Array.from() method to convert the string into an array of characters, and then use the slice() method to get the last N characters. Finally, we will join the array back into a string....