如何使用javascript正则表达式将字符串转换为驼峰大小写?

设备类名称或 设备类名或设备类名或设备类名

应该全部变成:equipmentClassName。


当前回答

基本的方法是用匹配大写或空格的正则表达式分割字符串。然后再把碎片粘回去。技巧将处理各种方式的正则表达式分割是破坏/奇怪的浏览器。有人编写了一个库来解决这些问题;我去找找。

这是链接:http://blog.stevenlevithan.com/archives/cross-browser-split

其他回答

基本的方法是用匹配大写或空格的正则表达式分割字符串。然后再把碎片粘回去。技巧将处理各种方式的正则表达式分割是破坏/奇怪的浏览器。有人编写了一个库来解决这些问题;我去找找。

这是链接:http://blog.stevenlevithan.com/archives/cross-browser-split

以下所有14个排列产生相同的“equipmentClassName”结果。

String.prototype.toCamelCase = function() { return this.replace(/[^a-z ]/ig, '') // Replace everything but letters and spaces. .replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, // Find non-words, uppercase letters, leading-word letters, and multiple spaces. function(match, index) { return +match === 0 ? "" : match[index === 0 ? 'toLowerCase' : 'toUpperCase'](); }); } String.toCamelCase = function(str) { return str.toCamelCase(); } var testCases = [ "equipment class name", "equipment class Name", "equipment Class name", "equipment Class Name", "Equipment class name", "Equipment class Name", "Equipment Class name", "Equipment Class Name", "equipment className", "equipment ClassName", "Equipment ClassName", "equipmentClass name", "equipmentClass Name", "EquipmentClass Name" ]; for (var i = 0; i < testCases.length; i++) { console.log(testCases[i].toCamelCase()); };

Coderbyte Camel案例解决方案

问题:

让函数CamelCase(str)接受传入的str参数,并以适当的驼峰格式返回,其中每个单词的第一个字母都大写(不包括第一个字母)。字符串将只包含字母和分隔符标点符号的某种组合。

例如:如果str是"BOB loves-coding",那么你的程序应该返回字符串bobLovesCoding。

解决方案:

函数CamelCase(str) { 返回str .toLowerCase () .replace (/ (^ \ w) + () / g (ltr) = > ltr.toUpperCase ()) .replace (/ [^ a-zA-Z] / g,”); } //保留此函数调用 console.log(CamelCase(“猫和*狗-真棒”)); console.log(CamelCase("a b c d-e-f%g"));

这建立在CMS的答案上,通过删除包括下划线在内的任何非字母字符,\w不会删除这些字符。

function toLowerCamelCase(str) {
    return str.replace(/[^A-Za-z0-9]/g, ' ').replace(/^\w|[A-Z]|\b\w|\s+/g, function (match, index) {
        if (+match === 0 || match === '-' || match === '.' ) {
            return ""; // or if (/\s+/.test(match)) for white spaces
        }
        return index === 0 ? match.toLowerCase() : match.toUpperCase();
    });
}

toLowerCamelCase("EquipmentClass name");
toLowerCamelCase("Equipment className");
toLowerCamelCase("equipment class name");
toLowerCamelCase("Equipment Class Name");
toLowerCamelCase("Equipment-Class-Name");
toLowerCamelCase("Equipment_Class_Name");
toLowerCamelCase("Equipment.Class.Name");
toLowerCamelCase("Equipment/Class/Name");
// All output e

我最后是这样做的:

String.prototype.toCamelCase = function(str) {
    return str
        .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
        .replace(/\s/g, '')
        .replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}

我试图避免将多个替换语句链接在一起。函数中有1 2 3美元。但是这种类型的分组很难理解,你提到的跨浏览器问题也是我从未想过的。