Reverse string is a popular algorithm question that can be asked during interviews. Here are five different ways to solve it:
Solution 1:
function reverse(string){
return string
.split('')
.reverse()
.join('');
}
Solution 2:
function reverse(string){
let revString = '';
for (let i = string.length - 1; i >= 0; i--){
revString = revString + string[i];
}
return revString
}
Solution 3:
function reverse(string){
let revString = '';
for (let i = 0; i <= string.length -1; i++){
revString = string[i] + revString;
}
return revString
}
Solution 4:
function reverse(string){
let revString ='';
for (let char of string){
revString = char + revString;
}
return revString
}
Solution 5:
function reverse(string){
let revString = '';
string.split('').forEach(char =>
revString = char + revString
);
return revString;
}
Top comments (1)