Skip to content

Instantly share code, notes, and snippets.

@tigerhawkvok
Last active August 29, 2015 14:22
Show Gist options
  • Save tigerhawkvok/5318ed29519d769ef3ef to your computer and use it in GitHub Desktop.
Save tigerhawkvok/5318ed29519d769ef3ef to your computer and use it in GitHub Desktop.
CoffeeScript toTitleCase
String::toTitleCase = ->
# From http://stackoverflow.com/a/6475125/1877527
str =
@replace /([^\W_]+[^\s-]*) */g, (txt) ->
txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()
# Certain minor words should be left lowercase unless
# they are the first or last words in the string
lowers = [
"A"
"An"
"The"
"And"
"But"
"Or"
"For"
"Nor"
"As"
"At"
"By"
"For"
"From"
"In"
"Into"
"Near"
"Of"
"On"
"Onto"
"To"
"With"
]
for lower in lowers
lowerRegEx = new RegExp("\\s#{lower}\\s","g")
str = str.replace lowerRegEx, (txt) -> txt.toLowerCase()
# Certain words such as initialisms or acronyms should be left
# uppercase
uppers = [
"Id"
"Tv"
]
for upper in uppers
upperRegEx = new RegExp("\\b#{upper}\\b","g")
str = str.replace upperRegEx, upper.toUpperCase()
str
String.prototype.toTitleCase = function() {
var lower, lowerRegEx, lowers, str, upper, upperRegEx, uppers, _i, _j, _len, _len1;
str = 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, _len = lowers.length; _i < _len; _i++) {
lower = lowers[_i];
lowerRegEx = new RegExp("\\s" + lower + "\\s", "g");
str = str.replace(lowerRegEx, function(txt) {
return txt.toLowerCase();
});
}
uppers = ["Id", "Tv"];
for (_j = 0, _len1 = uppers.length; _j < _len1; _j++) {
upper = uppers[_j];
upperRegEx = new RegExp("\\b" + upper + "\\b", "g");
str = str.replace(upperRegEx, upper.toUpperCase());
}
return str;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment