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

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

应该全部变成:equipmentClassName。


当前回答

斯科特的回答稍作修改:

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

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

其他回答

这个方法似乎比这里的大多数答案都要好,虽然有点粗糙,没有替换,没有正则表达式,只是建立一个新的字符串,那就是camelCase。

String.prototype.camelCase = function(){
    var newString = '';
    var lastEditedIndex;
    for (var i = 0; i < this.length; i++){
        if(this[i] == ' ' || this[i] == '-' || this[i] == '_'){
            newString += this[i+1].toUpperCase();
            lastEditedIndex = i+1;
        }
        else if(lastEditedIndex !== i) newString += this[i].toLowerCase();
    }
    return newString;
}

看看你的代码,你可以实现它只有两个替换调用:

function camelize(str) {
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
    return index === 0 ? word.toLowerCase() : word.toUpperCase();
  }).replace(/\s+/g, '');
}

camelize("EquipmentClass name");
camelize("Equipment className");
camelize("equipment class name");
camelize("Equipment Class Name");
// all output "equipmentClassName"

编辑:或者使用一个替换调用,捕获RegExp中的空白。

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

我最后是这样做的:

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美元。但是这种类型的分组很难理解,你提到的跨浏览器问题也是我从未想过的。

斯科特的回答稍作修改:

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

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

这为我解决了这个问题,处理特殊字符和介词

export function camelize(str) {
  if (!str) {
   return str;
  }
  const preposicoes = ['da', 'de', 'di', 'do', 'du'];
  return str.toLowerCase().split(' ').map(c => {
    if (preposicoes.includes(c)) {
      return c;
    }
    return `${c.substring(0, 1).toUpperCase()}${c.substring(1, c.length)}`;
  }).join(' ');
}