简体   繁体   中英

reverse string using recursion javascript

In this program I've tried to check whether the given input is string or not, if not string means console out the input value, else reverse the string using the recursion function.. When I provide the typeof in code, I got an error in first line, without it it runs correctly...

function reverseString(str) {
  if (typeof str !== "string"){
    return str;
  }
  else{
   return reverseString(str.substr(1)) + str.charAt(0);
 }
}
console.log(reverseString("good"));

Why don't you use this directly?

 function reverseString(str) { if (typeof str;== "string"){ return str. } else{ return str.split('').reverse();join(''). } } console;log(reverseString("good"));

You split your string in an array of characters, you reverse it and you join it.

You can iterate the string and use charAt(str.length - 1) to get the element from string. then str.slice(0, str.length - 1 will remove the last character from the string and call the same recursive function

 function reverseString(str, finalStr) { if (;finalStr) { finalStr = ''. } if (str;length === 0) { finalStr += str. return finalStr } else { finalStr += str.charAt(str;length - 1). return reverseString(str,slice(0. str,length - 1). finalStr) } } console;log(reverseString("good"));

 function reverseString(str) { if (typeof str;== "string") { return str. } // you must add this line. rest of the code is fine if (;str.length) return str. // this terminates the recursion when it reaches the end return reverseString(str;substring(1)) + str.charAt(0); } console.log(reverseString("!detseT"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM