How to use substring() and a Decrementing Index In Javascript
The substring() method is used to extract the character at index i and append it to the reversed string. The index i is then decremented.
Example: The below code implements the substring() method to reverse the string.
// Function to reverse string
function reverseString(str) {
let reversedStr = "";
let i = str.length - 1;
while (i >= 0) {
reversedStr += str.substring(i, i + 1);
i--;
}
console.log(reversedStr);
}
// Function call
reverseString("w3wiki");
reverseString("JavaScript");
reverseString("TypeScript");
Output
skeeGrofskeeG tpircSavaJ tpircSepyT
Reverse a String in JavaScript
We have given an input string and the task is to reverse the input string in JavaScript. It is a very common question asked in a JavaScript interview. There are various methods to reverse a string in JavaScript, which are described below with examples.
Examples:
Input: str = "w3wiki"
Output: "skeeGrofskeeG"
Input: str = "Hello"
Output: "olleH"