JavaScript Challenge (Part 3)
Today, we will be doing some string reversals!
Here are the directions:
Given a string, return a new string with the reversed order of characters
…and here are some examples”
--- Examples
reverse('apple') === 'leppa'
reverse('hello') === 'olleh'
reverse('Greetings!') === '!sgniteerG'
Try it out your own first and continue on once you have a solution in mind.
OK, hopefully you had some success with this challenge. We’re now going to walk through one possible solution.
This solution that we’re going to start off with is by the far easiest one. However, it’s also not necessarily the most obvious one.
The trick to solving this question is using a built in function that is included with the more recent versions of JavaScript, known as the reverse() method.
The reverse function right here will reverse all of the elements within a given array.
The reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes to first.
var a = ['one', 'two', 'three']';
a.reverse();console.log(a); //['three', 'two', 'one']
But remember, we were passed a string, not an array. So in order to use this very easy, very simple straightforward solution right here, we need to make sure that we are working with an array, not a string.
Fortunately, we can use a little method to convert our string into an array and call the reverse method on it, and then turn it back into a string.
Here is the implementation:
function reverse(str) {
const arr = str.split('');
arr.reverse();
return arr.join('');
}
We can also do a little bit of code cleanup to make this function a little bit more concise that it is.
Notice how right now we split our string into an array and assign it to a variable. In fact, we don’t really need to make use of this temporary variable.
function reverse(str) {
return str.split('').reverse().join('');
}
So, this is one possible solution to the reverse string challenge.