javascriptregexcoldfusion-8

How can I put names into title case in JavaScript?


I've been looking around on how to use JavaScript to set names to proper case, e.g. george mchall would become George McHall. I was able to find a write up on Codeproject on how to do this, as well as a person that intended it to do this:

function toProperCase(s){
    return s.toLowerCase().replace( /\b((m)(a?c))?(\w)/g,
    function($1, $2, $3, $4, $5) {
  if($2){
   return $3.toUpperCase()+$4+$5.toUpperCase();
  } 
  return $1.toUpperCase(); 
 });
}

This allows for what I'm looking for. But I need to be able to extend it further and add additional cases.

I found another page on John Gruber's site doing title case, but I'm only looking at doing names.

So, does anyone have an idea on extending it? I'm really just looking for a point in the right direction.

Edit: Since I seem to be hitting a wall here, maybe someone has a way to do it server side. This is at least for now using ColdFusion for the server side. I've seen a C# implementation, but I'm not able to move to C# at the moment.


Solution

  • How about this:

    if (str==str.toLowerCase() || str==str.toUpperCase())
      str = str.toTitleCase();
    

    Otherwise, leave it well alone!!!

    Edit: You could optionally split the string to weed out people holding the shift key for too long, like SMith.