This article is based on Free Code Camp Basic Algorithm Scripting ?Reverse a String?
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.
There are potentially tens of different ways to do it, excluding the built-in reverse function, as JavaScript does not have one.
Algorithm Challenge
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
reverString(“hello”) should become “olleh”reverseString(“Howdy”) should become “ydwoH”reverseString(“Greetings from Earth”) should return “htraE morf sgniteerG”
Reverse a String With Built-In Functions ? with split(), reverse() and join()
For this solution, you 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.
Here?s my solution, with embedded comments:
Chaining the three methods together:
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.
Three Ways to Reverse a String in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting ?Reverse a String?
medium.freecodecamp.com
You can follow me on Medium, Twitter, Github and LinkedIn, right after you click the green heart below 😉
?#?StayCurious?, ?#?KeepOnHacking? & ?#?MakeItHappen?!
Resources
- split() method ? MDN
- reverse() method ? MDN
- join() method ? MDN