正则替换小写为驼峰

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())
感觉不需要那个非捕获括号

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题