Reverse a String challenge
Reverse a String
Reverse a String challenge body
Reversing a string is one of the most frequently asked JavaScript question in the technical round of interview. Interviewers may ask you to write different ways to reverse a string, or they may ask you to reverse a string without using in-built methods, or they may even ask you to reverse a string using recursion. Below are my three most interesting ways to solve the problem of reversing a string in JavaScript.
Provided test cases:
- reverseString("hello") should return «olleh»
- reverseString("Howdy") should return «ydwoH»
- reverseString("Greetings from Earth") should return «htraE morf sgniteerG»
1. Reverse a String With Built-In Functions
For this solution, we will use three methods:
- String.prototype.split()
- Array.prototype.reverse()
- Array.prototype.join()
And the final code is:
function reverseString(str) { return str.split("").reverse().join(""); } reverseString("hello");
2. Reverse a String With a Decrementing For Loop
First of all we should create an empty string that will host the new created string. Then create the FOR loop. And finally return the reversed string. And this code looks like:
And the final code is:
function reverseString(str) { var newString = ""; for (var i = str.length - 1; i >= 0; i--) { newString += str[i]; } return newString; } reverseString("hello");
3. Reverse a String With Recursion
For this solution, we will use two methods:
- String.prototype.substr()
- String.prototype.charAt()
And the final code is:
function reverseString(str) { return (str === ' ') ? ' ' : reverseString(str.substr(1)) + str.charAt(0); } reverseString("hello");
reverseString ("") returned next result: «»