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

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

应该全部变成:equipmentClassName。


当前回答

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

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;
}


其他回答

这将把任何空格大小写字符串转换为thisWordsInCamelCase

function toCamelCase(str) {
  return str.toString() && str.split(' ').map((word, index) => {
    return (index === 0 ? word[0].toLowerCase() : word[0].toUpperCase()) + word.slice(1).toLowerCase()
  }).join('');
}

遵循@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, '' );
}

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

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

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

为了有效地创建一个将字符串的大小写转换为驼峰式大小写的函数,该函数还需要首先将每个字符串转换为小写,然后再将非第一个字符串的第一个字符转换为大写字母。

我的示例字符串是:

"text That I WaNt to make cAMEL case"

对于这个问题提供的许多其他解决方案返回这个:

"textThatIWaNtToMakeCAMELCase"

我认为应该是预期的,期望的输出将是这样的,其中所有的中间字符串大写字符首先转换为小写:

"textThatIWanrtToMakeCamelCase"

这可以在不使用任何replace()方法调用的情况下完成,通过使用String.prototype.split(), Array.prototype.map()和Array.prototype.join()方法:

≤ES5版本

function makeCamelCase(str) {
  return str
    .split(' ')
    .map((e,i) => i
      ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()
      : e.toLowerCase()
    )
    .join('')
}

makeCamelCase("text That I WaNt to make cAMEL case")
// -> "textThatIWanrtToMakeCamelCase" ✅

我将分解每一行的功能,然后以其他两种格式提供相同的解决方案——ES6格式和字符串格式。prototype方法,不过我建议不要像这样直接扩展内置的JavaScript原型。

讲解员

function makeCamelCase(str) {
  return str
    // split string into array of different words by splitting at spaces
    .split(' ')
    // map array of words into two different cases, one for the first word (`i == false`) and one for all other words in the array (where `i == true`). `i` is a parameter that denotes the current index of the array item being evaluated. Because indexes start at `0` and `0` is a "falsy" value, we can use the false/else case of this ternary expression to match the first string where `i === 0`.
    .map((e,i) => i
      // for all non-first words, use a capitalized form of the first character + the lowercase version of the rest of the word (excluding the first character using the slice() method)
      ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()
      // for the first word, we convert the entire word to lowercase
      : e.toLowerCase()
    )
    // finally, we join the different strings back together into a single string without spaces, our camel-cased string
    .join('')
}

makeCamelCase("text That I WaNt to make cAMEL case")
// -> "textThatIWanrtToMakeCamelCase" ✅

压缩ES6+(一行程序)版本

const makeCamelCase = str => str.split(' ').map((e,i) => i ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase() : e.toLowerCase()).join('')

makeCamelCase("text That I WaNt to make cAMEL case")
// -> "textThatIWanrtToMakeCamelCase" ✅

字符串。原型方法版本

String.prototype.toCamelCase = function() {
  return this
    .split(' ')
    .map((e,i) => i
      ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()
      : e.toLowerCase()
    )
    .join('')
}

"text That I WaNt to make cAMEL case".toCamelCase()
// -> "textThatIWanrtToMakeCamelCase" ✅
const toCamelCase = str =>
  str
    .replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase())
    .replace(/^\w/, c => c.toLowerCase());