1function reverseString(s){
2 return s.split("").reverse().join("");
3}
4reverseString("Hello");//"olleH"
1"this is a test string".split("").reverse().join("");
2//"gnirts tset a si siht"
3
4// Or
5const reverse = str => [...str].reverse().join('');
6
7// Or
8const reverse = str => str.split('').reduce((rev, char)=> `${char}${rev}`, '');
9
10// Or
11const reverse = str => (str === '') ? '' : `${reverse(str.substr(1))}${str.charAt(0)}`;
12
13// Example
14reverse('hello world'); // 'dlrow olleh'
1// hey buddy, here are different implementations, choose your favourite !!
2
3
4// best implementation
5const reverse = (str) => str.split("").reverse().join("");
6
7
8// explanation
9function reverse1(str) {
10 // turn string to array, each char of the string will be part of the
11 // array as an individual element
12 const arr = str.split("");
13
14 // swap all the indexes of the array
15 arr.reverse();
16
17 // join every element back together
18 const res = arr.join("");
19 return res;
20}
21
22
23// without using REVERSE method
24// recursive function
25function reverse2(str) {
26 let res = "";
27 for (let i = 0; i < str.length; i++) res = str[i] + res;
28 return res;
29}
30
31
32// using REDUCE ( high order array function )
33function reverse3(str) {
34 return str.split("").reduce((output, char) => {
35 return char + output;
36 }, "");
37}
1function reverseString(str) {
2 return str.split("").reverse().join("");
3}
4reverseString("hello");
1function reverse(str){
2 let reversed = "";
3 for (var i = str.length - 1; i >= 0; i--){
4 reversed += str[i];
5 }
6 return reversed;
7}