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

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

应该全部变成:equipmentClassName。


当前回答

编辑:现在工作在IE8没有变化。

编辑:我对camelCase到底是什么持少数意见(主角小写vs大写)。一般来说,社区认为开头小写字母是camel大小写,开头大写字母是pascal大小写。我创建了两个只使用正则表达式模式的函数。所以我们使用统一的词汇我已经改变了我的立场以配合大多数人。


我相信在这两种情况下你只需要一个正则表达式:

var camel = " THIS is camel case "
camel = $.trim(camel)
    .replace(/[^A-Za-z]/g,' ') /* clean up non-letter characters */
    .replace(/(.)/g, function(a, l) { return l.toLowerCase(); })
    .replace(/(\s.)/g, function(a, l) { return l.toUpperCase(); })
    .replace(/[^A-Za-z\u00C0-\u00ff]/g,'');
// Returns "thisIsCamelCase"

or

var pascal = " this IS pascal case "
pascal = $.trim(pascal)
  .replace(/[^A-Za-z]/g,' ') /* clean up non-letter characters */
  .replace(/(.)/g, function(a, l) { return l.toLowerCase(); })
  .replace(/(^.|\s.)/g, function(a, l) { return l.toUpperCase(); })
  .replace(/[^A-Za-z\u00C0-\u00ff]/g,'');
// Returns "ThisIsPascalCase"

在函数中:你会注意到,在这些函数中,replace是将任何非a-z与空格与空字符串交换。这是为大写创建单词边界。"hello-MY#world" -> "HelloMyWorld"

// remove \u00C0-\u00ff] if you do not want the extended letters like é
function toCamelCase(str) {
    var retVal = '';

    retVal = $.trim(str)
      .replace(/[^A-Za-z]/g, ' ') /* clean up non-letter characters */
      .replace(/(.)/g, function (a, l) { return l.toLowerCase(); })
      .replace(/(\s.)/g, function (a, l) { return l.toUpperCase(); })
      .replace(/[^A-Za-z\u00C0-\u00ff]/g, '');

    return retVal
}

function toPascalCase(str) {
    var retVal = '';

    retVal = $.trim(str)
      .replace(/[^A-Za-z]/g, ' ') /* clean up non-letter characters */
      .replace(/(.)/g, function (a, l) { return l.toLowerCase(); })
      .replace(/(^.|\s.)/g, function (a, l) { return l.toUpperCase(); })
      .replace(/[^A-Za-z\u00C0-\u00ff]/g, '');

    return retVal
}

注:

为了可读性,我保留了A-Za-z vs为模式(/[^A-Z]/ig)添加大小写不敏感标志(I)。 这可以在IE8中工作(srsly,谁还在使用IE8呢。)使用我在IE11、IE10、IE9、IE8、IE7和IE5中测试过的(F12)开发工具。适用于所有文档模式。 这将正确地对以空格或不以空格开头的字符串的第一个字母进行大小写区分。

享受

其他回答

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

我的示例字符串是:

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

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

String.prototype.toCamelCase = function(){ return this.replace(/\s(\w)/ig, function(all, letter){return letter. touppercase ();}) .replace (/ (^ \ w)、功能(1美元){返回1.美元tolowercase ()}); }; console.log(“设备名称”.toCamelCase ());

如果有人正在使用lodash,则有_.camelCase()函数。

_.camelCase('Foo Bar');
// → 'fooBar'

_.camelCase('--foo-bar--');
// → 'fooBar'

_.camelCase('__FOO_BAR__');
// → 'fooBar'

我知道这是一个老答案,但这处理空格和_ (lodash)

function toCamelCase(s){
    return s
          .replace(/_/g, " ")
          .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
          .replace(/\s/g, '')
          .replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}

console.log(toCamelCase("Hello world");
console.log(toCamelCase("Hello_world");

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