Reverse a string
Darren Jones
February 23, 2022
There is no built-in method to reverse a string, which seems a slightly bizarre omission. It’s easy to do though by converting the string into an array, using the built-in reverse method and then converting it back into a string.
Create the reverse function
javascript
const reverse = string =>
[...string].reverse().join(‘’)
reverse("hello")
// Output: "olleh"
How it works
This uses the spread operator to convert the string into an array where each element in the array is a separate character of the string, so for example, the string “hello” would become [“h”,”e”,”l”,”l”,”o”]
The reverse() method is then used to reverse the array, so it would become [“o”,”l”,”l”,”e”,”h”]
Finally, the join() method is used with an argument of an empty string. This combines all the elements of the array into a single string, so it would become “olleh”.