Skip to content

Instantly share code, notes, and snippets.

@jsdbroughton
Last active December 15, 2015 10:09
Show Gist options
  • Save jsdbroughton/5243904 to your computer and use it in GitHub Desktop.
Save jsdbroughton/5243904 to your computer and use it in GitHub Desktop.
Custom function for Google Sheets to Title case an array, range or single value. *Needs work* test function fails to correctly capitalise 'McCartney'
/*
* Function accepts a single ceel, array, 1D or 2D range Values.
*/
function titleCase(val) {
return processVal_(val);
}
function processVal_(val) {
var a;
if (val.constructor === Array) {
for (a = 0; a < val.length; a += 1) {
val[a] = processVal(val[a]);
}
} else {
val = toTitleCase(val);
}
return val;
}
function toTitleCase_(str) {
return str.replace(/([^\W_]+[^\s-]*) */g, function (match, p1, index, title) {
if (index > 0 && index + p1.length !== title.length &&
p1.search(smallWords) > -1 && title.charAt(index - 2) !== ":" &&
title.charAt(index - 1).search(/[^\s-]/) < 0) {
return match.toLowerCase();
}
if (p1.substr(1).search(/[A-Z]|\../) > -1) {
return match;
}
return match.charAt(0).toUpperCase() + match.substr(1);
});
}
function testTitleCase2() {
Logger.log(titleCase([['john lennon','paul mcCartney'],['robert scoble'],['tony blair','bobby tables','george bush']]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment