Thursday, March 10, 2011

Conversion to TitleCase

So I discovered in livedocs (Using Regular Expressions ) that you can pass a function as the 2nd parameter to a regular expression replace.

When a function name is used as the second parameter of the replace() method, the following are passed as parameters to the called function:
  • The matching portion of the string.
  • Any captured parenthetical group matches. The number of arguments passed this way varies depending on the number of captured parenthetical group matches. You can determine the number of captured parenthetical group matches by checking arguments.length - 3 within the function code.
  • The index position in the string where the match begins.
  • The complete string. 
therefore, to make a really easy convert to TitleCase method:


public static function toTitleCase(value:String):String
  {
   if (value)
   {
    //Convert to title case
    var titleCaseStr:String = value.toLowerCase();
    
    //http://livedocs.adobe.com/flex/3/html/help.html?content=12_Using_Regular_Expressions_10.html
    
    var toUpperFxn:Function = function (...parameters):String 
    {
     return parameters[1].toUpperCase()
    }

    //Find all word boundarys and then the first letter of the word... then call the function
    titleCaseStr = titleCaseStr.replace(/\b(\w)/g, toUpperFxn);
    
    return titleCaseStr;
   }

   return ""; 
  }

No comments:

Post a Comment