I recently had a project where I needed to quickly convert long strings of uppercase or lowercase text to Title Casing. Normally I would create a PHP script to do this, but they were all on different pages, so it had to be done manually. Rather than manually retype each, I wanted to create a JavaScript function to manage it.
I found some basic code which *mostly* worked to convert text. With some modification, I've developed a small text box with the following capabilities:
Here's the code for you to copy:
<input name="t" value="" type="text" size="50"
onclick="this.select();"
onkeyup="this.value=titleCaps(this.value);this.select();"
/>
<script>
function titleCaps(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;
title = lower(title);
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(/(['Õ])Sb/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);
}
</script>
Sign up for our daily email newsletter:
You must log in to post a comment.