简体   繁体   English

将驼峰式大小写转换为人类可读的字符串?

[英]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?是否有 reg exp 或 function 可以将驼峰大小写、css 和下划线转换为人类可读格式? 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" 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.这是基于 Ricks C 示例代码中的想法的 ActionScript 版本。 For JavaScript version remove the strong typing.对于 JavaScript 版本,删除强类型。 For example, change var value:String to var value .例如,将var value:String更改为var value Basically remove any declaration that starts with a semicolon, :String , :int , etc.基本上删除任何以分号、 :String:int等开头的声明。

/**
 * 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: JavaScript 版本:

/**
 * 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在无数评论之后,我意识到我提出了一些损坏的代码: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您可以使用String.replace替换函数,例如

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. hello-worldhello_world工作方式相似。

See JSFiddleJSFiddle

If using a library is an option, Lodash 's startCase or lowerCase might be options:如果使用库是一个选项, LodashstartCaselowerCase可能是选项:

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

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

Non elegant one liner using regex replaces with functions.使用正则表达式的非优雅单行替换为函数。

replace 1 - upper case first letter and remove _-替换 1 - 大写首字母并删除 _-

replace 2 - add space between lower case letters and upper case letters替换 2 - 在小写字母和大写字母之间添加空格

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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