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

sc4hvdpw  于 2023-01-16  发布在  Java
关注(0)|答案(7)|浏览(150)

有没有一个正则表达式或函数可以将驼峰式大小写、css和下划线转换成人类可读的格式?目前不需要支持非人类。对不起,外星人。:(
示例:
你好世界-〉"你好世界"
你好世界-〉"你好世界"
你好世界-〉"你好世界"

1qczuiv0

1qczuiv01#

按非词拆分;资本化加入:

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

yzuktlbb2#

用正则表达式提取所有单词,将它们大写,然后用空格连接。
正则表达式示例:

/^[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
hmae6n7t

hmae6n7t3#

以下是基于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;
}
uinbv5nw

uinbv5nw4#

您可以使用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

55ooxyrt

55ooxyrt5#

我不知道是否已经有一个内置的方法来做这件事,但是你可以循环通过字符串,每当你看到一个字符,你想这样做。
在您的情况下,如下所示:

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

yk9xbfzb6#

如果可以选择使用库,LodashstartCaselowerCase可能会很有用:
https://lodash.com/docs/#startCase
https://lodash.com/docs/#lowerCase

dtcbnfnu

dtcbnfnu7#

使用正则表达式的非优雅的一个行程序替换为函数。
替换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"));

相关问题