正则替换小写为驼峰

function toCamel(str) {

  return str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
     console.log($0, $1, $2)
    return   $1 + '_' + $2.toUpperCase();
  });

}
console.log(toCamel('test_to_camel'))

现在只能拿到test_To_Camel
想把第一个字母转大写的话正则该怎么改呢

阅读 2k
3 个回答
str.replace(/(?:^|_)\w/g, c => c.toUpperCase());

补充另一种正则

// => Test_To_Camel Abc_Def_G
'test_to_camel abc_def_g'.replace(/(\b|_)\w/g, item => item.toUpperCase());

'test_to_camel'.replace(/((^|_)\w)/g, c => c.toUpperCase())
感觉不需要那个非捕获括号

推荐问题