1//capitalize only the first letter of the string.
2function capitalizeFirstLetter(string) {
3 return string.charAt(0).toUpperCase() + string.slice(1);
4}
5//capitalize all words of a string.
6function capitalizeWords(string) {
7 return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
8};
1function capitalizeFirstLetter(string) {
2 return string.charAt(0).toUpperCase() + string.slice(1);
3}
4
5console.log(capitalizeFirstLetter('foo bar bag')); // Foo
1const lower = 'this is an entirely lowercase string';
2const upper = lower.charAt(0).toUpperCase() + lower.substring(1);
1const uppercaseWords = str => str.replace(/^(.)|\s+(.)/g, c => c.toUpperCase());
2
3// Example
4uppercaseWords('hello world'); // 'Hello World'
1function titleCase(str) {
2 var splitStr = str.toLowerCase().split(' ');
3 for (var i = 0; i < splitStr.length; i++) {
4 // You do not need to check if i is larger than splitStr length, as your for does that for you
5 // Assign it back to the array
6 splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
7 }
8 // Directly return the joined string
9 return splitStr.join(' ');
10}
11
12document.write(titleCase("I'm a little tea pot"));
1// includeAllCaps is optional and defaults to false
2// if includeAllCaps is set to true, it will Title Case words with all capital letters
3
4// includeMinorWords is optional and defaults to false
5// if includeMinorWords is set to true, it will minor words in the middle of the string
6
7function toTitleCase(str, includeAllCaps, includeMinorWords) {
8 includeAllCaps = (includeAllCaps ? (includeAllCaps == true ? true : false) : false);
9 includeMinorWords = (includeMinorWords ? (includeMinorWords == true ? true : false) : false);
10 var i, j, lowers;
11 str = str.replace(/([^\W_]+[^\s-]*) */g, function (txt) {
12 if (!/[a-z]/.test(txt) && /[A-Z]/.test(txt) && !includeAllCaps) {
13 return txt;
14 } else {
15 return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
16 }
17 });
18
19 if (includeMinorWords) {
20 return str;
21 } else {
22 // Certain minor words should be left lowercase unless
23 // they are the first or last words in the string
24 lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At',
25 'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'
26 ];
27 for (i = 0, j = lowers.length; i < j; i++)
28 str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'),
29 function (txt) {
30 return txt.toLowerCase();
31 });
32
33 return str;
34 }
35}
36
37toTitleCase("FOO bar"); // FOO Bar
38toTitleCase("FOO bar", true); // Foo Bar
39toTitleCase("a foo bar"); // A Foo Bar
40toTitleCase("a foo in bar"); // A Foo in Bar
41toTitleCase("foo of bar"); // Foo of Bar
42toTitleCase("foo of bar", false, true); // Foo Of Bar