Reverse a String in JavaScript: 2 Easy Methods

Reversing a string in JavaScript is a common operation that can be performed using different methods. In this article, we will show you two ways to reverse a string in JavaScript.

The first method uses the split(), reverse(), and join() methods to split the string into an array of characters, reverse the order of the characters in the array, and then join the characters back into a string. Here is an example:

// create a function that takes a string as an argument
function reverseString(str) {
// use the split() method to split the string into an array of characters
var strArray = str.split("");
// use the reverse() method to reverse the order of the characters in the array
var reversedArray = strArray.reverse();
// use the join() method to join the characters back into a string
var reversedString = reversedArray.join("");
// return the reversed string
return reversedString;
}
// call the function and pass a string as an argument
reverseString("hello"); // will return "olleh"

The second method uses the reduce() method to iterate over the characters in the string and build a new string in reverse order. Here is an example:

// create a function that takes a string as an argument
function reverseString(str) {
// use the reduce() method to iterate over the characters in the string
// and build a new string in reverse order
var reversedString = str.split("").reduce((rev, char) => char + rev, "");
// return the reversed string
return reversedString;
}
// call the function and pass a string as an argument
reverseString("hello"); // will return "olleh"

Both of these methods will reverse the string in JavaScript. You can choose the method that best suits your needs and use it in your code.


December 02, 2022
761