Reversing a string in JavaScript
We’ve all come across this question, one way or another. Whether it be simply doing some algorithms online for fun and trying to further our knowledge of coding, or we’ve met this question during a technical interview. This simple algorithm will almost always be on a technical interview for your interviewer to get a better understanding of how you work with strings.
Let’s dive into it
Let’s say we have a string of “coding”, and we would like to reverse this simple string. We would first start off by creating a function, and just simply naming it “reverse” and that function will have one parameter named “string”.
Like so:
After we’ve declared our function, we then want to invoke our function with an argument of the given string above: “coding”. As you know, nothing is going to happen when we invoke our function, since there’s no code inside of it.
We then want to proceed to write return, so our code will actually return the reversed string, and then follow up by using the .split(“”) method. The reason why we want to do that, is so we can transform the string into an array, and have each character of the string be an element of that array.
So far our code should look like so:
After we’ve split our string, we then want to use the .reverse() method on it. The reasoning for this is because the .reverse method can be used on arrays. Surprise! When we use the reverse method on our array, we should have our string go from this:
To this:
So far our code should be looking similar to this:
We’re getting there! We now have our array containing each character finally reversed. The final step to do now is to use the .join(“”) method. Reason why we want to use the join method is because the join method converts an array into a string. We want to convert our newly reversed array, and then join it so that we have our newly reversed string. After we’ve added our join method onto our reverse method, our code should look like this:
After all that has been done, we now have a simple reverse function. When we invoke the function and return our newly reversed string, which is: “gnidoc”.
I hope you enjoyed this quick simple blog on how to reverse a string. I’ve added some references on the methods it’s self, and will add some below.