Last active
December 28, 2015 03:39
-
-
Save erberg-snippets/7436352 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* 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