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

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

应该全部变成:equipmentClassName。


当前回答

return "hello world".toLowerCase().replace(/(?:(^.)|(\s+.))/g, function(match) {
    return match.charAt(match.length-1).toUpperCase();
}); // HelloWorld

其他回答

一个超级简单的方法,使用turboCommons库:

npm install turbocommons-es5

<script src="turbocommons-es5/turbocommons-es5.js"></script>

<script>
    var StringUtils = org_turbocommons.StringUtils;
    console.log(StringUtils.formatCase('EquipmentClass', StringUtils.FORMAT_LOWER_CAMEL_CASE));
    console.log(StringUtils.formatCase('Equipment className', StringUtils.FORMAT_LOWER_CAMEL_CASE));
    console.log(StringUtils.formatCase('equipment class name', StringUtils.FORMAT_LOWER_CAMEL_CASE));
    console.log(StringUtils.formatCase('Equipment Class Name', StringUtils.FORMAT_LOWER_CAMEL_CASE));
</script>

你也可以使用StringUtils。FORMAT_CAMEL_CASE和StringUtils。FORMAT_UPPER_CAMEL_CASE生成首字母大小写的变化。

更多信息:

将字符串转换为驼峰,UpperCamelCase或lowerCamelCase

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

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

我的示例字符串是:

"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" ✅

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

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

我最后是这样做的:

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