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

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

应该全部变成:equipmentClassName。


当前回答

这就是我的解决方案:

const toCamelWord = (word, idx) => Idx === 0 ? word.toLowerCase (): word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); const toCamelCase = text => 文本 .split (/ [_ - \] + /) . map (toCamelWord) . join (" "); console.log (toCamelCase(用户ID))

其他回答

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

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(' ');
}

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

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('');
}

以下所有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()); };

下面是一行代码:

const camelCaseIt = string => string.toLowerCase().trim().split(/[.\-_\s]/g).reduce((string, word) => string + word[0].toUpperCase() + word.slice(1));

它根据RegExp[中提供的字符列表拆分小写字符串。\-_\s](在[]中添加更多!)并返回一个单词数组。然后,它将字符串数组缩减为一个由首字母大写的单词组成的连接字符串。由于reduce没有初始值,它将从第二个单词开始大写第一个字母。

如果你想要PascalCase,只需在reduce方法中添加一个初始空字符串,”)。

这是解决方案,包括大写的第一个字母,如果第一个字母最初是大写的。

function toCamelCase(str){
  let newStr = "";
  if(str){
    let wordArr = str.split(/[-_]/g);
    for (let i in wordArr){
      if(i > 0){
        newStr += wordArr[i].charAt(0).toUpperCase() + wordArr[i].slice(1);
      }else{
        newStr += wordArr[i]
      }
    }
  }else{
    return newStr
  }
  return newStr;
}