There are several ways to reverse a string in JavaScript.

One way is to convert the string to an array using the split() method, then use the reverse() method on the array, and finally join the array back into a string using the join() method. Here’s an example:

let str = "hello";
let reversed = str.split("").reverse().join("");
console.log(reversed); // "olleh"

Another way is to use the for loop to iterate through the string and build a new string with the characters in reverse order:

let str = "hello";
let reversed = "";
for (let i = str.length - 1; i >= 0; i--) {
  reversed += str[i];
}
console.log(reversed); // "olleh"

You can also use reduce() method to build a new string with the characters in reverse order:

let str = "hello";
let reversed = str.split('').reduce((rev, char) => char + rev, '');
console.log(reversed); // "olleh"

Finally, you can use the spread operator to convert a string to an array, then use the reverse() method, and finally use the join() method to convert the reversed array back to a string:

let str = "hello";
let reversed = [...str].reverse().join('');
console.log(reversed); // "olleh"

All of these methods will reverse the string “hello” to “olleh”.

Also Read:

Categorized in: