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

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

应该全部变成:equipmentClassName。


当前回答

Lodash可以很好地做到这一点:

var _ = require('lodash');
var result = _.camelCase('toto-ce héros') 
// result now contains "totoCeHeros"

虽然lodash可能是一个“大”库(~4kB),但它包含了许多通常使用代码片段或自己构建的函数。

其他回答

不要使用String.prototype. tocamelcase(),因为String。原型是只读的,大多数js编译器会给你这个警告。

像我一样,那些知道字符串总是只包含一个空格的人可以使用一种更简单的方法:

let name = 'test string';

let pieces = name.split(' ');

pieces = pieces.map((word, index) => word.charAt(0)[index===0 ? 'toLowerCase' :'toUpperCase']() + word.toLowerCase().slice(1));

return pieces.join('');

祝你有愉快的一天。:)

快速的方法

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

斯科特的回答稍作修改:

toCamelCase = (string) ->
  string
    .replace /[\s|_|-](.)/g, ($1) -> $1.toUpperCase()
    .replace /[\s|_|-]/g, ''
    .replace /^(.)/, ($1) -> $1.toLowerCase()

现在它也替换了'-'和'_'。

遵循@Scott的可读性方法,做了一点微调

// convert any string to camelCase
var toCamelCase = function(str) {
  return str.toLowerCase()
    .replace( /['"]/g, '' )
    .replace( /\W+/g, ' ' )
    .replace( / (.)/g, function($1) { return $1.toUpperCase(); })
    .replace( / /g, '' );
}

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

function toCamelCase(str){
  return str.split(' ').map(function(word,index){
    // If it is the first word make sure to lowercase all the chars.
    if(index == 0){
      return word.toLowerCase();
    }
    // If it is not the first word only upper case the first char and lowercase the rest.
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  }).join('');
}