-
Notifications
You must be signed in to change notification settings - Fork 0
/
capitalize_first_letter.js
60 lines (43 loc) · 1.44 KB
/
capitalize_first_letter.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/* toTitleCase
Write a function that will capitalize every word in a sentence.
Example Input: "everything, everywhere, all at once"
Example Output: "Everything, Everywhere, All At Once"
*/
/*
First, write a function that takes in one word and
capitalizes the first letter of that word.
Example Input: "scrimba"
Example Output: "Scrimba"
Hint: Trying using slice() and .toUpperCase()
*/
function capitalizeWord(word) {
return word[0].toUpperCase() + word.slice(1);
}
/*
Now write a function that capitalizes every word in a sentence.
How can you reuse the function you just wrote?
*/
function toTitleCase(str) {
// split sentence into an array of words
const sentenceArr = str.split(' ');
// loop through the arrays of words and capitalizeWord func on each word
const capArr = sentenceArr.map(word => capitalizeWord(word));
// join sentence arr back into a string
return capArr.join()
}
// Test your functions
console.log(capitalizeWord("pumpkin"));
console.log(toTitleCase("pumpkin pranced purposefully across the pond"));
// This is how i solved it ->
// let str = "hello world! i am a developer";
// function capitalize(str){
// let str1 = str.split("");
// str1[0] = str1[0].toUpperCase();
// for(let i = 1; i < str1.length; i++){
// if(str1[i] === " "){
// str1[i + 1] = str1[i + 1].toUpperCase();
// }
// }
// return str1.join("");
// }
// console.log(capitalize(str));