问答

正则替换小写为驼峰

作者:admin 2021-05-06 我要评论

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

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

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
想把第一个字母转大写的话正则该怎么改呢

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

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • 正则替换小写为驼峰

    正则替换小写为驼峰

  • 关于java工厂模式的作用?

    关于java工厂模式的作用?

  • Gson解析的@Expose()注释使用问题

    Gson解析的@Expose()注释使用问题

  • Vagrant安装过失败

    Vagrant安装过失败

腾讯云代理商
海外云服务器