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.

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;
}

Comments

One response to “AS3 – Split a camel case string”

  1. Olaf Krüger Avatar
    Olaf Krüger

    This saved my day, thank you!!
    Very nice designed blog, keep it up!

Leave a Reply