how to reverse a string in javascript without using reverse method code example
Example 1: javascript reverse a string
function reverseString(s){
return s.split("").reverse().join("");
}
reverseString("Hello");//"olleH"
Example 2: how to reverse a string in javascript without using reverse method
function reverseString(str) {
var newString = "";
for (var i = str.length - 1; i >= 0; i--) {
newString += str[i];
}
return newString;
}
reverseString('hello');
Example 3: reverse a string javascript
var s = userInput[0];
var rev = [];
for(let i=0;i<s.length;i++)
{
rev.push(s[s.length-1-i]);
}
console.log(rev.join(""));
Example 4: how to reverse a string in javascript without using reverse method
function reverseString(str) {
if (str === "") // This is the terminal case that will end the recursion
return "";
else
return reverseString(str.substr(1)) + str.charAt(0);
/*
First Part of the recursion method
You need to remember that you won’t have just one call, you’ll have several nested calls
Each call: str === "?" reverseString(str.subst(1)) + str.charAt(0)
1st call – reverseString("Hello") will return reverseString("ello") + "h"
2nd call – reverseString("ello") will return reverseString("llo") + "e"
3rd call – reverseString("llo") will return reverseString("lo") + "l"
4th call – reverseString("lo") will return reverseString("o") + "l"
5th call – reverseString("o") will return reverseString("") + "o"
Second part of the recursion method
The method hits the if condition and the most highly nested call returns immediately
5th call will return reverseString("") + "o" = "o"
4th call will return reverseString("o") + "l" = "o" + "l"
3rd call will return reverseString("lo") + "l" = "o" + "l" + "l"
2nd call will return reverserString("llo") + "e" = "o" + "l" + "l" + "e"
1st call will return reverserString("ello") + "h" = "o" + "l" + "l" + "e" + "h"
*/
}
reverseString("hello");
Example 5: how to reverse a string in javascript without using reverse method
function reverseString(str) {
return str.split("").reverse().join("");
}
reverseString("hello");
Example 6: how to reverse a string in javascript without using reverse method
function reverseString(str) {
if (str === "")
return "";
else
return reverseString(str.substr(1)) + str.charAt(0);
}
reverseString("hello");