JavaScript Title Case

by CarcaBot on July 24, 2009 · 0 comments

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:

  • Converts the text inside the box to title case.
  • It leaves certain smaller words lower cased (configurable)
  • As soon as you paste text with your keys (CTRL+V or CMD+V), it does the conversion
  • 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(/(['Õ])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>

    Previous post:

    Next post: