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')); // Foo
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
1String.prototype.capitalize = function() {
2 return this.charAt(0).toUpperCase() + this.slice(1);
3}
4