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//as a function
4function reverseString(string){
5return string.split("").reverse().join("");}
6reverseString("test string");
7//"gnirts tset"
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//with built-in method
2let string = "We are going to reverse a string with built-in method.";
3let reversed = string.split("").reverse().join("");
4console.log(reversed);
5
6//with the for loop
7let string = "We are going to reverse a string with the for loop.";
8function reverse (string){
9 let reversed = "";
10 for(let char of string){
11 reversed = char + reversed;
12 }
13 return reversed;
14}
15console.log(reverse(string));
16
17//with the spread operator
18let string = "We are going to reverse a string with the spread operator.";
19let reversed = [...string].reverse().join("");
20console.log(reversed);
21
22//with iteration
23let string = "We are going to reverse a string with iteration.";
24function reverse(string) {
25 for (var reversed = "", i = string.length - 1; i >= 0; i--) {
26 reversed += string[i];
27 }
28 return reversed;
29console.log(reverse(string));
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}
1function reverseString(str) {
2 return str
3 .split("")
4 .reverse()
5 .join("");
6}
7