How to Get the Last Two Characters of a String in JavaScript
const str = 'Coding Beauty';
const last2 = str.slice(-2);
console.log(last2); // ty
// When we pass a negative number as an argument,
// slice() counts backward from the last string character to find the equivalent index.
// So passing -2 to slice() specifies a start index of str.length - 2.
const last2Again = str.slice(str.length - 2);
console.log(last2Again); // ty
// Note
// We can use substring() in place of slice() to get the first two characters of a string:
const str = 'Coding Beauty';
const last2 = str.substring(str.length - 2);
console.log(last2); // ty
// However, we have to manually calculate the start index ourselves with str.length - 2,
// which makes the code less readable.
// This is because unlike slice(), substring() uses 0 as the start index if a negative number is passed.
const str = 'Coding Beauty';
// -2 is negative, 0 used as start index
const notLast2 = str.substring(-2);
console.log(notLast2); // Coding Beauty
const myString = "linto.yahoo.com.";
const stringLength = myString.length; // this will be 16
console.log('lastChar: ', myString.charAt(stringLength - 1)); // this will be the string
Run code snippet
find the length and the last character of string in js
// Get The Length Of The String.
function strLength(x){
var counter = 0;
while(x[counter] !== undefined){
counter++;
}
return counter;
}
var str = prompt("Write your string ...",''); // Get String From User.
var The_Length = strLength(str); //
var lastChar = counter - 1; // The Index Of Last Letter.
console.log(`The Length Of Your String is ${counter}`);
console.log(`The Last Char In Your String Is ${str[lastChar]}`);