Array Methods
This is the simplest and most commonly used method.
const str = "hello";
const reversed = str.split("").reverse().join("");
console.log(reversed); // "olleh"
- The
split(“”)converts the string into an array of characters, something like this:[“h”, “e”, “l”, ‘l’, “o”]. - With
reverse(), you reverse the array. - And with
join(“”), it joins this array to a stringolleh.
With a `for`
const str = "hello";
let reversed = "";
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
console.log(reversed); // "olleh"
With spread operator
const str = "hello";
const reversed = [...str].reverse().join("");
console.log(reversed); // "olleh"
For most cases, the first method using split will suffice; it is short and readable.