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

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

应该全部变成:equipmentClassName。


当前回答

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

其他回答

这就是我的解决方案:

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))

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

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

如果不需要regexp,你可能想看看我很久以前为Twinkle做的以下代码:

String.prototype.toUpperCaseFirstChar = function() {
    return this.substr( 0, 1 ).toUpperCase() + this.substr( 1 );
}

String.prototype.toLowerCaseFirstChar = function() {
    return this.substr( 0, 1 ).toLowerCase() + this.substr( 1 );
}

String.prototype.toUpperCaseEachWord = function( delim ) {
    delim = delim ? delim : ' ';
    return this.split( delim ).map( function(v) { return v.toUpperCaseFirstChar() } ).join( delim );
}

String.prototype.toLowerCaseEachWord = function( delim ) {
    delim = delim ? delim : ' ';
    return this.split( delim ).map( function(v) { return v.toLowerCaseFirstChar() } ).join( delim );
}

我没有做任何性能测试,regexp版本可能更快,也可能不会更快。

大多数答案不处理unicode字符,例如重音字符。

如果你想处理unicode和重音,在任何现代浏览器中都可以使用以下方法:

camelCase = s => s
   .replace( /(?<!\p{L})\p{L}|\s+/gu,
              m => +m === 0 ? "" : m.toUpperCase() )
   .replace( /^./, 
             m => m?.toLowerCase() );

以下是一些解释:

因为问题要求第一个字符是小写的,所以必须调用第二个replace。 第一个replace调用标识任何跟在任何非字母后面的unicode字母(相当于\b\w,但适用于非ASCII字母)。为此,u标志(unicode)是必要的。

注意,这将保持大写字母不变。如果您的输入文本包含首字母缩略词,这很有用。

e.g.

console.log(camelCase("Shakespeare in FR is être ou ne pas être");
// => 'ShakespeareInFRIsÊtreOuNePasÊtre'

如果您想要纯驼峰大小写,其中首字母缩写变成小写,您可以先将输入文本小写。

不要使用String.prototype. tocamelcase(),因为String。原型是只读的,大多数js编译器会给你这个警告。

像我一样,那些知道字符串总是只包含一个空格的人可以使用一种更简单的方法:

let name = 'test string';

let pieces = name.split(' ');

pieces = pieces.map((word, index) => word.charAt(0)[index===0 ? 'toLowerCase' :'toUpperCase']() + word.toLowerCase().slice(1));

return pieces.join('');

祝你有愉快的一天。:)