This article is based on Free Code Camp Basic Algorithm Scripting “Reverse a String”
Reverse the provided string.
You may need to turn the string into an array before you can reverse it.
Your result must be a string.
Provided test cases
- reverseString(“hello”) should become “olleh”
- reverseString(“Howdy”) should become “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: the String.prototype.split() method, the Array.prototype.reverse() method and the Array.prototype.join() method.
- The split() method splits a String object into an array of string by separating the string into sub strings.
- The reverse() method reverses an array in place. The first array element becomes the last and the last becomes the first.
- The join() method joins all elements of an array into a string.
Chaining the three methods together:
2. Reverse a String With a Decrementing For Loop
3. Reverse a String With Recursion
For this solution, we will use two methods: the String.prototype.substr() method and the String.prototype.charAt() method.
- The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.
"hello".substr(1); // "ello"
- The charAt() method returns the specified character from a string.
"hello".charAt(0); // "h"
The depth of the recursion is equal to the length of the String. This solution is not the best one and will be really slow if the String is very long and the stack size is of major concern.
Conditional (Ternary) Operator:
I hope you found this helpful. This is part of my “How to Solve FCC Algorithms” series of articles on the Free Code Camp Algorithm Challenges, where I propose several solutions and explain step-by-step what happens under the hood.
In this article, I’ll explain how to solve freeCodeCamp’s “Repeat a string repeat a string” challenge. This involves…
In this article, I’ll explain how to solve freeCodeCamp’s “Confirm the Ending” challenge.
This article is based on Free Code Camp Basic Algorithm Scripting “Factorialize a Number”
This article is based on Free Code Camp Basic Algorithm Scripting “Check for Palindromes”.
This article is based on Free Code Camp Basic Algorithm Scripting “Find the Longest Word in a String”.
This article is based on Free Code Camp Basic Algorithm Scripting “Title Case a Sentence”.
If you have your own solution or any suggestions, share them below in the comments.
#StayCurious, #KeepOnHacking & #MakeItHappen!