简体   繁体   中英

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"

Split by non-words; capitalize; join:

function toCapitalizedWords(name) {
    var words = name.match(/[A-Za-z][a-z]*/g) || [];

    return words.map(capitalize).join(" ");
}

function capitalize(word) {
    return word.charAt(0).toUpperCase() + word.substring(1);
}

Extract all words with a regular expression. Capitalize them. Then, join them with spaces.

Example regexp:

/^[a-z]+|[A-Z][a-z]*/g

/   ^[a-z]+      // 1 or more lowercase letters at the beginning of the string
    |            // OR
    [A-Z][a-z]*  // a capital letter followed by zero or more lowercase letters
/g               // global, match all instances  

Example function:

var camelCaseToWords = function(str){
    return str.match(/^[a-z]+|[A-Z][a-z]*/g).map(function(x){
        return x[0].toUpperCase() + x.substr(1).toLowerCase();
    }).join(' ');
};

camelCaseToWords('camelCaseString');
// Camel Case String

camelCaseToWords('thisIsATest');
// This Is A Test

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

I don't know if there is already a built in method to do this but you could loop through the string and every time you see a character that you want to split on do so.

In your case something like:

    my_str = 'helloWorld';
    returnString = '';
    for(var i = 0; i < my_str.length; i++) {
        if(i == 0) {
            returnString += (my_str[i] + 32); // capitalize the first character
        }
        else if(my_str[i] > 'A' || my_str[i] < 'Z') {
            returnString += ' ' + my_str[i]; // add a space
        }
        else if(my_str[i] == '-' || my_str[i] == '_') {
            returnString += ' ';
        }
        else {
            returnString += my_string[i];
        }
    }

   return returnString;

Edit:

After the numerous comments I have come to realize that I put up some broken code :P

Here is a tested version of it:

my_str = 'helloWorld';

function readable(str) {
    // and this was a mistake about javascript/actionscript being able to capitalize
    // by adding 32
    returnString = str[0].toUpperCase();

    for(var i = 1; i < str.length; i++) {
        // my mistakes here were that it needs to be between BOTH 'A' and 'Z' inclusive
        if(str[i] >= 'A' && str[i] <= 'Z') {
            returnString += ' ' + str[i];
        }
        else if(str[i] == '-' || str[i] == '_') {
            returnString += ' ';
        }
        else {
            returnString += str[i];
        }
    }

    return returnString;
}

You can use a replacement function for String.replace , eg

function capitalize(s) {
    return s[0].toUpperCase() + s.slice(1);
}

function replacer1(match, p1, p2, p3, offset, s) {
    return p1 + capitalize(p2) + ' ' + p3;
}

var s1 = "helloWorld";
var r1 = s1.replace(/(^|[^a-z])([a-z]+)([A-Z])/, replacer1);
console.log(r1);

hello-world and hello_world work similar.

See JSFiddle

If using a library is an option, Lodash 's startCase or lowerCase might be options:

https://lodash.com/docs/#startCase

https://lodash.com/docs/#lowerCase

Non elegant one liner using regex replaces with functions.

replace 1 - upper case first letter and remove _-

replace 2 - add space between lower case letters and upper case letters

 var titleCase = s => s .replace(/(^|[_-])([az])/g, (a, b, c) => c.toUpperCase()) .replace(/([az])([AZ])/g, (a, b, c) => `${b} ${c}`); console.log(titleCase("helloWorld")); console.log(titleCase("hello-world")); console.log(titleCase("hello_world"));

 const result = _.chain("hello-world").snakeCase().split("_").map(w => _.capitalize(w)).join(" ").value() console.log(result)
 <script src=" https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js "></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM