File tree 1 file changed +45
-0
lines changed
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Reversing a String in JavaScript.
2
+
3
+ // Approach1
4
+
5
+ function reverse ( str ) {
6
+ return str . split ( "" ) . reverse ( ) . join ( "" ) ;
7
+ }
8
+
9
+ console . log ( reverse ( "Namit" ) ) ;
10
+
11
+ // Approach 2(Using ES6 syntax)
12
+
13
+ function reverse ( str ) {
14
+ return [ ...str ] . reverse ( ) . join ( "" ) ;
15
+ }
16
+
17
+ console . log ( reverse ( "Namit" ) ) ;
18
+
19
+ // Approach3(Without using in-built methods)
20
+
21
+ function reverse ( str ) {
22
+ let newString = "" ;
23
+ for ( let i = str . length - 1 ; i >= 0 ; i -- ) {
24
+ newString = newString + str [ i ] ;
25
+ }
26
+ return newString ;
27
+ }
28
+ console . log ( reverse ( "Namit" ) ) ;
29
+
30
+ // Approach4(using recursion)
31
+
32
+ function reverse ( str ) {
33
+ if ( str === "" ) {
34
+ return "" ;
35
+ }
36
+ return reverse ( str . substr ( 1 ) ) + str . charAt ( 0 ) ;
37
+ }
38
+ console . log ( reverse ( "Namit" ) ) ;
39
+
40
+ // Approach5(Using reduce function)
41
+
42
+ function reverse ( str ) {
43
+ return str . split ( "" ) . reduce ( ( acc , item ) => item + acc , "" ) ;
44
+ }
45
+ console . log ( reverse ( "Namit" ) ) ;
You can’t perform that action at this time.
0 commit comments