将驼峰案例转换为人类可读的字符串?

时间:2014-01-15 20:45:22

标签: javascript actionscript-3 actionscript

是否有一个reg exp或函数可以将camel case,css和underscore转换为人类可读的格式?它目前不需要支持非人类。对不起外星人。 :(

示例:

helloWorld - > “你好世界”
你好世界 - > “你好世界”
hello_world - > “你好世界”

7 个答案:

答案 0 :(得分:16)

按非单词分开;利用;加入:

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

答案 1 :(得分:6)

使用正则表达式提取所有单词。资本化他们。然后,用空格加入它们。

示例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  

示例功能:

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

答案 2 :(得分:3)

这是基于Ricks C示例代码的想法的ActionScript版本。对于JavaScript版本,删除强类型。例如,将var value:String更改为var value。基本上删除任何以分号: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版本:

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

答案 3 :(得分:2)

我不知道是否已有内置方法来执行此操作,但您可以遍历字符串,每次看到要分割的字符时都这样做。

在你的情况下:

    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;

编辑:

在众多评论之后,我逐渐意识到我提出了一些破碎的代码:P

以下是它的测试版本:

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

答案 4 :(得分:2)

您可以replacement function使用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-worldhello_world的工作方式类似。

请参阅JSFiddle

答案 5 :(得分:1)

如果选择使用库,则可以选择Lodash的{​​{1}}或startCase

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

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

答案 6 :(得分:1)

使用正则表达式替换函数的非优雅单行。

替换 1 - 大写首字母并删除 _-

replace 2 - 在小写字母和大写字母之间添加空格

var titleCase = s => s
  .replace(/(^|[_-])([a-z])/g, (a, b, c) => c.toUpperCase())
  .replace(/([a-z])([A-Z])/g, (a, b, c) => `${b} ${c}`);

console.log(titleCase("helloWorld"));
console.log(titleCase("hello-world"));
console.log(titleCase("hello_world"));