Recursive string reversal function in javascript?

2020-02-04 20:23发布

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?

12条回答
兄弟一词,经得起流年.
2楼-- · 2020-02-04 20:48

According to the MDN Web Docs, you should use substring() instead of substr():

Warning: Although String.prototype.substr(…) is not strictly deprecated (as in "removed from the Web standards"), it is considered a legacy function and should be avoided when possible. It is not part of the core JavaScript language and may be removed in the future. If at all possible, use the substring() method instead.

Additionally, if no index is provided as a parameter to charAt(), the default is 0.

Therefore, we can write a recursive one-liner to reverse a string using a ternary operator and by applying the logic described above:

const reverse_string = s => s === '' ? '' : reverse_string(s.substring(1)) + s.charAt();

console.log(reverse_string('Hello, world!')); // !dlrow ,olleH

查看更多
唯我独甜
3楼-- · 2020-02-04 20:49

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.

查看更多
在下西门庆
4楼-- · 2020-02-04 20:52

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, '');
};
查看更多
闹够了就滚
5楼-- · 2020-02-04 20:52
function reverse(str) {
  if(str.charAt(0) === ''){
    return "";
  }
  return str.charAt(str.length -1) + reverse(str.substring(0,str.length-1));
}
查看更多
Bombasti
6楼-- · 2020-02-04 20:53

The base case that I am using for exiting the recursion is when the the length decrease to 0

On each recursive call we will take out the last character of the string and append it with the result that we will get from recursive call of a string, which is smaller in size as the last character is removed using slice.

function reverse(str){
 if(str.length===0)
    return "";

return str[str.length-1]+reverse(str.slice(0,str.length-1));
}
查看更多
闹够了就滚
7楼-- · 2020-02-04 20:54

//call this function with the string as parameter

function strrev(str) {
    return str.length !== 1 ? strrev(str.slice(1))+str[0] : str;
}
查看更多
登录 后发表回答