DEV Community

stuxnat
stuxnat

Posted on

5 Solutions: Reverse String Algorithm in JS

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('');
}
Enter fullscreen mode Exit fullscreen mode

Solution 2:

function reverse(string){
    let revString = '';

    for (let i = string.length - 1; i >= 0; i--){
        revString = revString + string[i];
    }
    return revString
  }
Enter fullscreen mode Exit fullscreen mode

Solution 3:

function reverse(string){
    let revString = '';

    for (let i = 0; i <= string.length -1; i++){
        revString = string[i] + revString; 
    }
    return revString
  }

Enter fullscreen mode Exit fullscreen mode

Solution 4:

 function reverse(string){
      let revString =''; 
    for (let char of string){
        revString = char + revString; 
    }
    return revString
  }
Enter fullscreen mode Exit fullscreen mode

Solution 5:

function reverse(string){
    let revString = ''; 
    string.split('').forEach(char => 
        revString = char + revString
    );
    return revString;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ
const reverse = ([...string]) => string.reverse().join('')
Enter fullscreen mode Exit fullscreen mode