Basic Algorithm Scripting – Reverse a String

Basic Algorithm Scripting – Reverse a String

Problem Statement (Reverse a string) :

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.

Solution :

function reverseString(str) {

    return str.split('').reverse().join('');

}

Explanation :

You can’t directly reverse a string, but what you could do, is convert the string to something that can be reversed and then again convert the reversed into string.

We know that we can reverse an array in javascript. That is what I have done in my code.  , this is going to create an array of the string with every character in the string at one index of the array (even the spaces).

str.split()  , this is going to create an array of the string with every character in the string at one index of the array (even the spaces).

We are doing the chaining of expressions in this solution. The array generated from split() function is sent to reverse() function which reverses the array. Now, the resultant array is converted to string using join() function, which is the opposite of split(). And the last we get our result as reversed string.

You can find more problems solved in here : FreeCodeCamp – Basic Algorithm Scripting – Solved

www.000webhost.com