-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCapitalizeWords.js
More file actions
36 lines (27 loc) · 841 Bytes
/
CapitalizeWords.js
File metadata and controls
36 lines (27 loc) · 841 Bytes
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
// Given a String, create a function on String that converts the first character
// of each word to Uppercase and rest characters are lowercase.
/*
Input:
sampleString="hello My name is NAMIT"
Output:
"Hello My Name Is Namit"
*/
// Approach 1
String.prototype.toCapitalize = function () {
const words = this.split(" ");
let tempArray = [];
for (let i = 0; i < words.length; i++) {
let word =
words[i].charAt(0).toUpperCase() + words[i].slice(1).toLowerCase();
tempArray.push(word);
}
return tempArray.join(" ");
};
console.log("hello My name is NAMIT".toCapitalize());
// Approach 2
String.prototype.toCapitalize = function () {
return this.split(" ")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(" ");
};
console.log("hello My name is NAMIT".toCapitalize());