Skip to content

Instantly share code, notes, and snippets.

@cziem
Created July 5, 2018 20:32
Show Gist options
  • Save cziem/8a58ba7f389eeaecabdce5a98ff8f621 to your computer and use it in GitHub Desktop.
Save cziem/8a58ba7f389eeaecabdce5a98ff8f621 to your computer and use it in GitHub Desktop.
Reverse a string
// 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