Created
July 5, 2018 20:32
-
-
Save cziem/8a58ba7f389eeaecabdce5a98ff8f621 to your computer and use it in GitHub Desktop.
Reverse a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Method 1 | |
const reverseString = str => { | |
let newString = ""; | |
for (let char of str) { | |
newString = char + newString; | |
} | |
return newString; | |
}; | |
// method 2 using reduce | |
function reverseStrn(str) { | |
return str.split("").reduce((rev, char) => char + rev, ""); | |
} | |
// by Recursion | |
function reverseStrn(str) { | |
if (str === "") return ""; | |
else return reverseStrn(str.substr(1)) + str.charAt(0); | |
} | |
// using a for loop | |
function reverseStr(str) { | |
let newStr = ""; | |
for (let i = str.length - 1; i >= 0; i--) { | |
newStr += str[i]; | |
return newStr; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment