javascriptactionscript-3actionscript

Convert camel case to human readable string?


Is there a reg exp or function that will convert camel case, css and underscore to human readable format? It does not need to support non-humans at this time. Sorry aliens. :(

Examples:

helloWorld -> "Hello World"
hello-world -> "Hello World"
hello_world -> "Hello World"


Solution

  • Here is the ActionScript version based on the idea from Ricks C example code. For JavaScript version remove the strong typing. For example, change var value:String to var value. Basically remove any declaration that starts with a semicolon, :String, :int, etc.

    /**
     * Changes camel case to a human readable format. So helloWorld, hello-world and hello_world becomes "Hello World". 
     * */
    public static function prettifyCamelCase(value:String=""):String {
        var output:String = "";
        var len:int = value.length;
        var char:String;
    
        for (var i:int;i<len;i++) {
            char = value.charAt(i);
    
            if (i==0) {
                output += char.toUpperCase();
            }
            else if (char !== char.toLowerCase() && char === char.toUpperCase()) {
                output += " " + char;
            }
            else if (char == "-" || char == "_") {
                output += " ";
            }
            else {
                output += char;
            }
        }
    
        return output;
    }
    

    JavaScript version:

    /**
     * Changes camel case to a human readable format. So helloWorld, hello-world and hello_world becomes "Hello World". 
     * */
    function prettifyCamelCase(str) {
        var output = "";
        var len = str.length;
        var char;
    
        for (var i=0 ; i<len ; i++) {
            char = str.charAt(i);
    
            if (i==0) {
                output += char.toUpperCase();
            }
            else if (char !== char.toLowerCase() && char === char.toUpperCase()) {
                output += " " + char;
            }
            else if (char == "-" || char == "_") {
                output += " ";
            }
            else {
                output += char;
            }
        }
    
        return output;
    }