Skip to content

Instantly share code, notes, and snippets.

@erberg-snippets
Last active December 28, 2015 03:39
Show Gist options
  • Save erberg-snippets/7436352 to your computer and use it in GitHub Desktop.
Save erberg-snippets/7436352 to your computer and use it in GitHub Desktop.
/**
* Changes the first character of each word to upper case, and any other characters to lowercase.
* @return {String} String formatted as a title.
*/
String.prototype.toTitleCase = function() {
var title = this.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At',
'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'
];
for (i = 0; i < lowers.length; i++) {
title = title.replace(new RegExp('\\s' + lowers[i], 'g'),
function(txt) {
return txt.toLowerCase();
});
}
uppers = ['Id', 'Tv', 'Ii', 'Iii', 'Iv', 'Vi', 'Vii', 'Viii', 'Ix', 'Ny'];
for (i = 0; i < uppers.length; i++) {
title = title.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'),
uppers[i].toUpperCase());
}
return title;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment