Iterate through string in reverse order and push letters to array, then join the array
function reverse1(str) {
if(!str || str.length < 2 || typeof str !== "string") {
return new Error("Not a valid input");
}
const backwards = [];
for (let i = str.length; i > -1; i--) {
backwards.push(str[i]);
}
return backwards.join('');
}
Use split, reverse, and join methods
function reverse2(str) {
return str.split().reverse().join();
}
Use ES6 arroe function and spread operator to copy as well as convert the string to array and then reverse and join
reverse3 = str => [...str].reverse().join('');
Call the three functions
console.log(reverse1("Hello World!"));
console.log(reverse2("Hello World!"));
console.log(reverse3("Hello World!"));
Output
!dlroW olleH
Hello World!
!dlroW olleH
Comments
Post a Comment