DEV Community

Discussion on: Reverse a String - Four JavaScript Solutions

Collapse
 
bugmagnet profile image
Bruce Axtens • Edited

This recursion thing is pretty cool. Here's another approach both as a String.prototype and as a standalone function:

String.prototype.flip2 = function() {
  if (1 >= this.length) return this;
  return (
    this.substr(-1) +
    this.substr(1, this.length - 2).flip2() +
    this.substr(0, 1)
  );
};

function flip2(string) {
  if (1 >= string.length) return string;
  return (
    string.substr(-1) +
    flip2(string.substr(1, string.length - 2)) +
    string.substr(0, 1)
  );
}

var x = "lewd i did live - evil did i dwel".flip2();
var y = flip2("lewd i did live - evil did i dwel");

The approach is to take the first character and put it last, take the last character and put it first, and do that to the stuff in the middle.

It's been through the Closure Compiler, thus the 1 >= this.length.