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

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

应该全部变成:equipmentClassName。


当前回答

从上驼峰格式("TestString")到下驼峰格式("TestString"),而不使用正则表达式(让我们面对现实吧,正则表达式是邪恶的):

'TestString'.split('').reduce((t, v, k) => t + (k === 0 ? v.toLowerCase() : v), '');

其他回答

一个有趣的方法是通过dataset属性。

函数camelize(dashString) { let el = document.createElement('div') el.setAttribute(数据——+ dashString”) 返回种(el.dataset) [0] } camelize('x-element') // 'xElement'

您可以使用以下解决方案:

String.prototype.toCamelCase = function(){ return this.replace(/\s(\w)/ig, function(all, letter){return letter. touppercase ();}) .replace (/ (^ \ w)、功能(1美元){返回1.美元tolowercase ()}); }; console.log(“设备名称”.toCamelCase ());

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

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

上面的答案很简洁,但它不能处理所有的边缘情况。对于任何需要更强大的实用程序的人,没有任何外部依赖:

function camelCase(str) {
    return (str.slice(0, 1).toLowerCase() + str.slice(1))
      .replace(/([-_ ]){1,}/g, ' ')
      .split(/[-_ ]/)
      .reduce((cur, acc) => {
        return cur + acc[0].toUpperCase() + acc.substring(1);
      });
}

function sepCase(str, sep = '-') {
    return str
      .replace(/[A-Z]/g, (letter, index) => {
        const lcLet = letter.toLowerCase();
        return index ? sep + lcLet : lcLet;
      })
      .replace(/([-_ ]){1,}/g, sep)
}

// All will return 'fooBarBaz'
console.log(camelCase('foo_bar_baz'))
console.log(camelCase('foo-bar-baz'))
console.log(camelCase('foo_bar--baz'))
console.log(camelCase('FooBar  Baz'))
console.log(camelCase('FooBarBaz'))
console.log(camelCase('fooBarBaz'))

// All will return 'foo-bar-baz'
console.log(sepCase('fooBarBaz'));
console.log(sepCase('FooBarBaz'));
console.log(sepCase('foo-bar-baz'));
console.log(sepCase('foo_bar_baz'));
console.log(sepCase('foo___ bar -baz'));
console.log(sepCase('foo-bar-baz'));

// All will return 'foo__bar__baz'
console.log(sepCase('fooBarBaz', '__'));
console.log(sepCase('foo-bar-baz', '__'));

演示在这里:https://codesandbox.io/embed/admiring-field-dnm4r?fontsize=14&hidenavigation=1&theme=dark

快速的方法

function toCamelCase(str) {
    return str[0].toUpperCase() + str.substr(1).toLowerCase();
}