String Reversal
For this challenge, I'm going to keep it simple.
Directions
Given a string, return a new string with the reversed
order of characters.
Examples
reverse(‘plane’) === ‘enalp’
reverse(‘hello’) === ‘olleh’
Let's create the function and pass a string as an argument.
function reverseString(str){}
Now, there is some information we need to discuss to be able to use the reverse function for javascript.
Array.prototype.reverse()
The reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first. With this being said the reverse method is an array method and is not going to work for a string.
if we try to cheat and do the following
function reverse(str){str.reverse();}reverse('plane')
the output will be TypeError str.reverse is not a function.
In order to make this work, we need to convert the string to an array. So let’s discuss the other method we will be using.
String.prototype.split()
The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method’s call.
So, let's convert the string to an array.
function reverseString(str){ const array = str.split('');
}
So far, we already have an array and we need to reverse it by using the array method reverse.
function reverseString(str){
const array = str.split('');
arr.reverse();}
Now we need to convert this array back to a string, for this we need the join method.
Array.prototype.join()
The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
Let's convert the array back to a string.
function reverse(str) { const arr = str.split(''); arr.reverse(); return arr.join('');}
Since this is the last piece of code we need a return keyword to return the result.
This will look like this:
function reverse(str) { const arr = str.split(''); arr.reverse(); return arr.join('')}reverse("banana") ---> ananab
reverse("batman") ---> namtab
I’m making this new series to practice my algorithms skills and hope this helps someone. Thank you and happy coding.