CodeWar(JavaScript)---Convert string to camel case

9 篇文章 0 订阅

Convert string to camel case

问题:
Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).

Examples
toCamelCase("the-stealth-warrior") // returns "theStealthWarrior"

toCamelCase("The_Stealth_Warrior") // returns "TheStealthWarrior"

翻译(来自有道翻译):

完成方法/函数,以便将破折号/下划线分隔的单词转换为驼峰式大小写。只有当原始单词大写时,输出中的第一个单词才应该大写(称为大写驼峰大小写,也通常称为帕斯卡大小写)。

例子
toCamelCase("the-stealth-warrior") // returns "theStealthWarrior"

toCamelCase("The_Stealth_Warrior") // returns "TheStealthWarrior"

个人解题代码

//思路:将str切割放入tmp中,for循环遍历当出现"-"、"_"时让他们后一位字母变成大写
//最后将tmp中元素合成进str并输出
function toCamelCase(str){
  var tmp = str.split('');
  for(var i = 0 ; i < tmp.length ; i++){
    if(tmp[i] == "-"||tmp[i] == "_"){
      tmp[i+1]=tmp[i+1].toUpperCase();
      tmp.splice(i,1)
    }
  }
  str = tmp.join('');

  return str
}

高亮回答

function toCamelCase(str){
      var regExp=/[-_]\w/ig;
      return str.replace(regExp,function(match){
            return match.charAt(1).toUpperCase();
       });
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值