Last active
August 29, 2015 14:03
-
-
Save jjanusch/0e699c0273e2e69042bf to your computer and use it in GitHub Desktop.
Prototypes String to allow for any string to be capitalized. Can also take into account English articles by using the 'title' type. Warning: automatically lower cases the entire string, so words like "McDonald's" will be out put as "Mcdonald's". See bottom of Gist for usage examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String.prototype.capitalize = function(type) { | |
var str = this.toLowerCase(); | |
if (type) { | |
var nArr = [], | |
articles = ["a", "an", "and", "as", "at", "but", "by", "etc", "for", "in", "into", "is", "nor", "of", "off", "on", "onto", "or", "so", "the", "to", "unto", "via"], | |
arr = str.split(' '), | |
i = 0, | |
value; | |
for (i; i < arr.length; i++) { | |
value = arr[i]; | |
if (i == 0 || i == arr.length - 1 || type == 'all' || (type == 'title' && articles.indexOf(value) < 0)) { | |
nArr.push(value.charAt(0).toUpperCase() + value.slice(1)); | |
} | |
else { | |
nArr.push(value); | |
} | |
} | |
return nArr.join(' '); | |
} | |
return str.charAt(0).toUpperCase() + str.slice(1); | |
} | |
"ThiS sHoulD Be PROPERLY capitalized and all the if and or end capital articleS Should NOT BE".capitalize('title'); | |
// output: "This Should Be Properly Capitalized and All the If and or End Capital Articles Should Not Be" | |
"ThiS sHoulD Be PROPERLY capitalized and all the if and or end capital articleS Should NOT BE".capitalize('all'); | |
// output: "This Should Be Properly Capitalized And All The If And Or End Capital Articles Should Not Be" | |
"ThiS sHoulD Be PROPERLY capitalized and all the if and or end capital articleS Should NOT BE".capitalize(); | |
//output: "This should be properly capitalized and all the if and or end capital articles should not be" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment