-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathReverseString.js
45 lines (33 loc) · 849 Bytes
/
ReverseString.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Reversing a String in JavaScript.
// Approach1
function reverse(str) {
return str.split("").reverse().join("");
}
console.log(reverse("Namit"));
// Approach 2(Using ES6 syntax)
function reverse(str) {
return [...str].reverse().join("");
}
console.log(reverse("Namit"));
// Approach3(Without using in-built methods)
function reverse(str) {
let newString = "";
for (let i = str.length - 1; i >= 0; i--) {
newString = newString + str[i];
}
return newString;
}
console.log(reverse("Namit"));
// Approach4(using recursion)
function reverse(str) {
if (str === "") {
return "";
}
return reverse(str.substr(1)) + str.charAt(0);
}
console.log(reverse("Namit"));
// Approach5(Using reduce function)
function reverse(str) {
return str.split("").reduce((acc, item) => item + acc, "");
}
console.log(reverse("Namit"));