July 10, 2022 ‐ 1 min read
.reverse() method for arrays does prove to be useful when needing to reverse a string as well however.
In order to reverse a string we can first split it into an array for single characters, then reverse the array and finally glue it back together using the
let str = "stressed"; str = str.split(""); //=> ['s', 't', 'r', 'e', 's', 's', 'e', 'd'] str.reverse(); //=> ['d', 'e', 's', 's', 'e', 'r', 't', 's'] str = str.join(""); //=> "desserts"
Note that the
.reverse() method reverses the array in-place. Therefor there is no need to do a reassignment as we do with
We can chain these method calls together into a one-liner as well:
let str = "stressed".split("").reverse().join(""); //=> "desserts"