How to use reduce() and split() Methods In Javascript
The split() method divides the string into an array of characters, and reduce() combines the characters in reverse order using the accumulator, effectively reversing the original string.
Example: The below code explains the use of the reduce and split method to reverse a string.
function reverseString(str){
const reversedString =
str.split("").reduce((acc, char) => char + acc, "");
console.log(reversedString);
}
reverseString("w3wiki");
reverseString("JavaScript");
reverseString("TypeScript");
Output
skeeGrofskeeG tpircSavaJ tpircSepyT
Reverse a String in JavaScript
We have given an input string and the task is to reverse the input string in JavaScript. It is a very common question asked in a JavaScript interview. There are various methods to reverse a string in JavaScript, which are described below with examples.
Examples:
Input: str = "w3wiki"
Output: "skeeGrofskeeG"
Input: str = "Hello"
Output: "olleH"