Skip to content

Instantly share code, notes, and snippets.

@nnutter
Created June 24, 2012 06:28
Show Gist options
  • Save nnutter/2982010 to your computer and use it in GitHub Desktop.
Save nnutter/2982010 to your computer and use it in GitHub Desktop.
Bookmarklet-Ready Code to Title Case Selected Text
// Ported to JavaScript By John Resig - http://ejohn.org/ - 21 May 2008
// Original by John Gruber - http://daringfireball.net/2008/05/title_case - 10 May 2008
// License: http://www.opensource.org/licenses/mit-license.php
function toTitleCase(title){
var small = "(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|v[.]?|via|vs[.]?)";
var punct = "([!\"#$%&'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]*)";
var parts = [], split = /[:.;?!] |(?: |^)["Ò]/g, index = 0;
while (true) {
var m = split.exec(title);
parts.push( title.substring(index, m ? m.index : title.length)
.replace(/\b([A-Za-z][a-z.'Õ]*)\b/g, function(all){
return /[A-Za-z]\.[A-Za-z]/.test(all) ? all : upper(all);
})
.replace(RegExp("\\b" + small + "\\b", "ig"), lower)
.replace(RegExp("^" + punct + small + "\\b", "ig"), function(all, punct, word){
return punct + upper(word);
})
.replace(RegExp("\\b" + small + punct + "$", "ig"), upper));
index = split.lastIndex;
if ( m ) parts.push( m[0] );
else break;
}
return parts.join("").replace(/ V(s?)\. /ig, " v$1. ")
.replace(/([’'Õ])S\b/ig, "$1s")
.replace(/\b(AT&T|Q&A)\b/ig, function(all){
return all.toUpperCase();
});
};
function lower(word){
return word.toLowerCase();
}
function upper(word){
return word.substr(0,1).toUpperCase() + word.substr(1);
}
// Remaining is original code authored by nnutter - 11 Jun 2012
// License: http://www.opensource.org/licenses/mit-license.php
var t, s, e;
t = document.activeElement;
s = t.selectionStart;
e = t.selectionEnd;
if (e > s) {
var l, m, r;
l = t.value.substr(0, s);
m = t.value.substr(s, (e - s));
r = t.value.substr(e, (t.value.length - e));
t.value = l + toTitleCase(m) + r;
} else {
t.value = toTitleCase(t.value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment