Reverse a String
Learn how to solve the freeCodeCamp algorithm 'Reverse a String' using the String.split(), Array.reverse(), and Array.join() JavaScript methods.
In this freeCodeCamp algorithm, we need to take a given String
and then reverse it while making sure the result also returns a String
.
Hint: Convert the string into an array before reversing it.
Requirements
reverseString("hello")
should return a stringreverseString("hello")
should become"olleh"
reverseString("Howdy")
should become"ydwoH"
reverseString("Greetings from Earth")
should become"htraE morf sgniteerG"
Psuedocode
If we break the problem down into smaller pieces, the requirements ultimately look something like this:
Reading the Docs
Great developers are often very resourceful. Given that just about all of the programming information you could imagine is already online, chances are you should be able to find the answers to your questions fairly quickly.
If you're not already familiar with the Mozilla Developer Network then it's about time you bookmark it.
MDN is the resource of all resources for JavaScript. I mean, the dude who co-founded Mozilla actually invented JavaScript.
.split(), .reverse(), and .join()
In our pseuedocode, we noted that we needed a way to split the string up, ideally into individual characters. Lucky for us, JavaScript already has a built in method that will allow us to do this.
Here are a few resources on how to use the .split()
, .reverse()
, and .join()
method:
String.prototype.split()
Array.prototype.reverse()
Array.prototype.join()
Solving the Algorithm
Create the Function
First, let's start by creating the function that will accept an argument str
, that will get passed through and returned as the reverse.
Using the String.split()
Method
Next we can setup our function to utilize the .split()
method we learned about from the MDN Docs. This allows us to split the inputted string, and return it as an array.
Using the Array.reverse()
Method
Next we'll use the .reverse()
method which, hence the name, allows us to reverse an array.
Using the Array.join()
Method
Lastly, let's take a look at the .join()
method where we can take the items of an array and join them together to output a String
.
And there it is!
Using methods that are built in to the JavaScript library we're able to reverse a string! Pretty cool, huh?
Refactoring
All in all, we were able to get the job done with only a few lines of code. The fact of the matter is that even though our solution was only a few lines of code, we can refactor this down to a one liner by using chaining. Let's take a look:
Bonus Solution
Let's take a look at how we can solve this algorithm if we didn't have access to the .reverse()
method:
Wrapping Up
Hopefully you found this to be a helpful walkthrough of this freeCodeCamp algorithm on how to reverse a string!
Shoot me an email at tim@timwheeler.com
with any questions and if you enjoyed this, stay tuned and subscribe below! 👇
Help us improve our content