JavaScript Code

JavaScript Title Case

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:

  1. Converts the text inside the box to title case.
  2. It leaves certain smaller words lower cased (configurable)
  3. As soon as you paste text with your keys (CTRL+V or CMD+V), it does the conversion
  4. It automatically selects all text in the box for you, for easy copying

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(/(['Õ])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);
}
</script>
Share

4 Comments

  1. Ahhhh! Free code that I can use and not have to lift a finger. Thanks. 🙂

  2. hey, nice code, how would you be able to do the same thing except type in the textbox and use a button to convert the string entered in said textbox

  3. Nice code, I was wondering though; what would you change if you had people that wanted to enter the string in the text box and then hit a button to convert it.

  4. I love this script! I ran into a snag where the word has html entities in it (protégé), and it treats the &'s like a word boundary, so the end result is "ProtéGé." Any suggestions?

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image