1. For loop
This is the simplest way we can think of right now. In this method we will use a descending loop to loop through each letter of the string and create a new string using the string addition method.
Another way to solve the above problem is to use a for…of loop. This is a new loop introduced in ES6. This loop has the function of looping through each element in a string or an array. Using this method seems to help your code reduce errors and tidier than the above.
2. Use reverse() method
Because reversed() medthod is a method that returns the inverse order of an array and it is only used in an array, to be able to use this method to solve the problem, we need to use it with the other two methods are split() and join().
3. Spread Operator
This is similar to the above, but it’s worth it anyway. That is, using the new Spread (…) operator in ES6. Spread Operator can decompose characters in a string and convert the string into an array…
Therefore, in this case we will use the Spread operator to separate the characters in the input string.
4. Reduce() method
Reduce() is a method used for arrays, so you need to use split() to split the string and convert that string into an array before you can use this method.
And the last way is to use recursive method. Recursive is understood as a function that calls itself, in this problem I will use the substr () method to cut the string gradually and use access string syntax to add the cut-out character to the last string. If it is hard to imagine, just copy the code to test and run it.
Hope you learn well.
Categories: Learn programming