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

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

应该全部变成:equipmentClassName。


当前回答

这建立在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

其他回答

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

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

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

const toCamelCase = str =>
  str
    .replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase())
    .replace(/^\w/, c => c.toLowerCase());

在斯科特的具体情况下,我会这样说:

String.prototype.toCamelCase = function() {
    return this.replace(/^([A-Z])|\s(\w)/g, function(match, p1, p2, offset) {
        if (p2) return p2.toUpperCase();
        return p1.toLowerCase();        
    });
};

'EquipmentClass name'.toCamelCase()  // -> equipmentClassName
'Equipment className'.toCamelCase()  // -> equipmentClassName
'equipment class name'.toCamelCase() // -> equipmentClassName
'Equipment Class Name'.toCamelCase() // -> equipmentClassName

正则表达式将匹配以大写字母开头的第一个字符,以及空格后面的任何字母字符,即在指定的字符串中匹配2或3次。

通过将正则表达式添加到/^([A-Z])|[\s-_](\w)/g,还可以简化连字符和下划线类型的名称。

'hyphen-name-format'.toCamelCase()     // -> hyphenNameFormat
'underscore_name_format'.toCamelCase() // -> underscoreNameFormat

我的ES6方法:

const camelCase = str => {
  let string = str.toLowerCase().replace(/[^A-Za-z0-9]/g, ' ').split(' ')
                  .reduce((result, word) => result + capitalize(word.toLowerCase()))
  return string.charAt(0).toLowerCase() + string.slice(1)
}

const capitalize = str => str.charAt(0).toUpperCase() + str.toLowerCase().slice(1)

let baz = 'foo bar'
let camel = camelCase(baz)
console.log(camel)  // "fooBar"
camelCase('foo bar')  // "fooBar"
camelCase('FOO BAR')  // "fooBar"
camelCase('x nN foo bar')  // "xNnFooBar"
camelCase('!--foo-¿?-bar--121-**%')  // "fooBar121"