Skip to content

Commit 7e4c7ce

Browse files
committed
Adding Capitalize
1 parent b45dab9 commit 7e4c7ce

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

capitalize/capitalize.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
// Solution No 1
11+
12+
function capitalize(str) {
13+
let words = [];
14+
15+
for(let word of str.split('')) {
16+
words.push(word[0].toUpperCase() + word.slice(1));
17+
}
18+
19+
return words.join(' ');
20+
}
21+
22+
// Solution No. 2
23+
24+
function capitalize(str) {
25+
let result = str[0].toUpperCase();
26+
27+
for( let i=1; i < str.length; i++) {
28+
if(str[i-1] === ' '){
29+
result += str[i].toUpperCase();
30+
} else {
31+
result += str[i];
32+
}
33+
}
34+
35+
return result;
36+
}

capitalize/directions.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# --- Directions
2+
3+
Write a function that accepts a string. The function should
4+
capitalize the first letter of each word in the string then
5+
return the capitalized string.
6+
7+
# --- Examples
8+
9+
* capitalize('a short sentence') should return 'A Short Sentence'
10+
* capitalize('a lazy fox') should return 'A Lazy Fox'
11+
* capitalize('look, it is working!') should return 'Look, It Is Working!'
12+
13+
14+
# --- Solutions
15+
16+
// Solution No 1
17+
18+
function capitalize(str) {
19+
let words = [];
20+
21+
for(let word of str.split('')) {
22+
words.push(word[0].toUpperCase() + word.slice(1));
23+
}
24+
25+
return words.join(' ');
26+
}
27+
28+
// Solution No. 2
29+
30+
function capitalize(str) {
31+
let result = str[0].toUpperCase();
32+
33+
for( let i=1; i < str.length; i++) {
34+
if(str[i-1] === ' '){
35+
result += str[i].toUpperCase();
36+
} else {
37+
result += str[i];
38+
}
39+
}
40+
41+
return result;
42+
}

0 commit comments

Comments
 (0)