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 argumentfunction reverseString(str) {// use the split() method to split the string into an array of charactersvar strArray = str.split("");// use the reverse() method to reverse the order of the characters in the arrayvar reversedArray = strArray.reverse();// use the join() method to join the characters back into a stringvar reversedString = reversedArray.join("");// return the reversed stringreturn reversedString;}// call the function and pass a string as an argumentreverseString("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 argumentfunction reverseString(str) {// use the reduce() method to iterate over the characters in the string// and build a new string in reverse ordervar reversedString = str.split("").reduce((rev, char) => char + rev, "");// return the reversed stringreturn reversedString;}// call the function and pass a string as an argumentreverseString("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.
Read more
December 04, 2022
JavaScriptDecember 04, 2022
JavaScriptDecember 01, 2022
JavaScript