Skip to content Skip to sidebar Skip to footer

Recursive String Reversal Function In Javascript?

I'm a pretty experienced frontend engineer with a weak CS background. I'm trying to get my head around the concept of recursion. Most of the examples and purported explanations I c

Solution 1:

Something like:

function reverse (str) {
    if (str === "") {
        return"";
    } else {
        return reverse(str.substr(1)) + str.charAt(0);
    }
}

So the function is recursive as it calls itself to do the work.

Solution 2:

A tail recursive version, just for kicks (even though JavaScript doesn't perform tail call elimination):

function reverse(str) {
  function r(s, acc) {
    return (s.length == 0) ? acc : r(s.substr(1), s.charAt(0) + acc);
  };
  return r(str, '');
};

Solution 3:

One line of code using ternary operators you can easily reverse it.

Explanation: if string exists (if not null) then return recursion otherwise stop the recursion.

  function reverseString(str) {
    return (str ? reverseString(str.substring(1)) + str.charAt(0) : str);
  }

Function call:

console.log(reverseString('hello'));

Solution 4:

A 25% faster function: jsperf.com

functionReverse(str) {
  if (str === null) {
    returnnull;
  }
  if (str.length <= 1) {
    return str;
  }
  var first = str[0];
  var last = str[str.length - 1];
  var str1 = Reverse(str.substring(1, str.length - 1));
  return last + str1 + first;
}

var result = Reverse("a really serious string of nothingness making call stack to explode");

Solution 5:

function reverse(str) {
  if(str.charAt(0) === ''){
    return"";
  }
  returnstr.charAt(str.length -1) + reverse(str.substring(0,str.length-1));
}

Post a Comment for "Recursive String Reversal Function In Javascript?"