File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
udemy-interview-bootcamp-course Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ // --- Directions
2
+ // Write a function that accepts a string. The function should
3
+ // capitalize the first letter of each word in the string then
4
+ // return the capitalized string.
5
+ // --- Examples
6
+ // capitalize('a short sentence') --> 'A Short Sentence'
7
+ // capitalize('a lazy fox') --> 'A Lazy Fox'
8
+ // capitalize('look, it is working!') --> 'Look, It Is Working!'
9
+
10
+ function capitalize ( string ) {
11
+ return string . split ( ' ' ) . map ( ( word ) => {
12
+ return word . substr ( 0 , 1 ) . toUpperCase ( ) + word . substr ( 1 ) ;
13
+ } ) . join ( ' ' ) ;
14
+ }
15
+
16
+
17
+ // console.log(capitalize('a short sentence')); //'A Short Sentence'
18
+ // console.log(capitalize('a lazy fox')); // 'A Lazy Fox'
19
+ // console.log(capitalize('look, it is working!')); // 'Look, It Is Working!'
20
+
21
+
22
+ function capitalizeSolution1 ( string ) {
23
+ if ( string . length === 0 ) return '' ;
24
+
25
+ let result = string [ 0 ] . toUpperCase ( ) ;
26
+
27
+ for ( let i = 1 ; i < string . length ; i ++ ) {
28
+ if ( result [ i - 1 ] === " " ) {
29
+ result += string [ i ] . toUpperCase ( ) ;
30
+ } else {
31
+ result += string [ i ] ;
32
+ }
33
+ }
34
+
35
+ return result ;
36
+ }
37
+
38
+ console . log ( capitalizeSolution1 ( 'a short sentence' ) ) ; //'A Short Sentence'
39
+ console . log ( capitalizeSolution1 ( 'a lazy fox' ) ) ; // 'A Lazy Fox'
40
+ console . log ( capitalizeSolution1 ( 'look, it is working!' ) ) ; // 'Look, It Is Working!'
You can’t perform that action at this time.
0 commit comments