1. 程式人生 > >codewars解題筆記 —— 將字串轉駝峰,單詞首字母大寫

codewars解題筆記 —— 將字串轉駝峰,單詞首字母大寫

題目: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.
(完成方法/函式,以便將破折號/下劃線分隔的單詞轉換為駱駝殼。輸出中的第一個詞只有大寫的大寫字母才大寫。)

Examples:

toCamelCase("the-stealth-warrior") 

// returns "theStealthWarrior"

toCamelCase("The_Stealth_Warrior")

// returns "TheStealthWarrior"

我的答案:

function toCamelCase(str){
  let arr = str.split(/-|_/g);
  let str2 = ''
  arr.forEach((item, index) => {
      console.log(item)
      if (index !== 0) {
          let a = item.charAt(0)
          item = item.replace(a, a.toUpperCase())
      }
      console.log(item)
      str2 = str2.concat(item)
  })
  return str2
}
票數最高答案:
function toCamelCase(str){
      var regExp=/[-_]\w/ig;
      return str.replace(regExp,function(match){
            return match.charAt(1).toUpperCase();
       });
}


思考:

1、首先別人的程式碼清晰簡潔,畢竟是別人的程式碼。

2、解題思路突破慣性思維。我拿到題目想到的解題思路是先將 小破折號或者下劃線去掉,將幾個單詞拆開,然後找到除了第一個單詞其他單詞的首字母,將其變成大寫,再將改好的單詞拼成字串。別人的解題思路是找到 小破折號或者下劃線和後面的第一個單詞,直接替換成這第一個單詞的大寫,完成

ex:  -s =》 S

         -b =》 B

3、正則:/[-_]\w/ig

                [-_]  表示: [...] 位於括號之內的任意字元   引申 =》 [^...] 不在括號之中的任意字元 

                \w    表示:任何單字字元, 等價於[a-zA-Z0-9]    引申  =》 \W 任何非單字字元,等價於[^a-zA-Z0-9] 

                i       表示:執行大小寫不敏感的匹配 

                g      表示:執行一個全域性的匹配,簡而言之,就是找到所有的匹配,而不是在找到第一個之後就停止了 

4、replace

          str = str.replace(/正則/ig,"新值")

          注意:replace無權修改原字串,必須用變數接住替換後生成的新字串

          高階:根據不同的關鍵詞,動態替換不同的新值

         str = str.replace(/正則/ig,function(kw){

             kw //本次找到的關鍵詞

             return 根據kw計算出新的替換值

          })

      衍生操作:

     1、刪除:將找到的關鍵詞替換為""

     2、格式化:將原字串中的關鍵詞按新的格式重新組合

          2步:1、用正則將原字串中的內容分組

                   2、用replace按新格式重新組合各個分組的內容

          ex:"19831226" =>"1983年12月26日"

               birth.replace(/(\d{4})(\d{2})(\d{2})/,"$1年$2月$3日")

               其中:$n可獲得第n個()分組對應的子字串。

      答案中拿到的  match ,就是匹配正則後的 -s

match.charAt(1).toUpperCase();
        這一步,就是 -s =》S

       最後返回需要的替換 字母