AS3 – Split a camel case string

This is a little helper function which takes a string in camel case (camelCase) or pascal case (PascalCase) and splits it into separate words. The capitaliseFirst parameter will capitalise the first character in the first word if the string is in camel case.

For example “thisIsCamelCase” will become “This Is Camel Case”.

Thanks to this regular expression on Regexr.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function splitCamelCase(str:String, capitaliseFirst:Boolean):String
{
    var r:RegExp = /(^[a-z]|[A-Z0-9])[a-z]*/g;
    var result:Array = str.match(r);
   
    if (result.length > 0)
    {
        if (capitaliseFirst)
            result[0] = String(result[0]).charAt(0).toUpperCase() + String(result[0]).substring(1);
       
        return result.join(" ");
    }
   
    return str;
}
Posted toActionScript Flash