How to useloop and string concatenation in Javascript
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:
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!
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
Contact Us