Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 can find just aren't explaining it in a way I find easy to understand.

I set myself a task of writing a function that will reverse a string recursively. I know there has to be a base condition (i.e. the solution is found), but I can't figure out how to actually write something like this and could use a demo to study.

Could someone provide a sample function?

like image 347
Geuis Avatar asked Feb 01 '11 05:02

Geuis


People also ask

How can a given string be reversed using recursion in JavaScript?

function reverseString(str) { if (str === "") // This is the terminal case that will end the recursion return ""; else return reverseString(str. substr(1)) + str.

Is there a reverse method for string in JavaScript?

Example 2: Reverse a String Using built-in Methods split("") gives ["h", "e", "l", "l", "o"] . The string elements are reversed using the reverse() method. arrayStrings. reverse() gives ["o", "l", "l", "e", "h"] .


2 Answers

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.

like image 60
Tom Avatar answered Oct 23 '22 07:10

Tom


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, '');
};
like image 34
maerics Avatar answered Oct 23 '22 09:10

maerics