如何在 JavaScript 中將字串轉換為駝峰式?


駝峰式是編寫句子的一種方法,其中每一個詞或縮寫以大寫字母開頭,單詞之間不留空格或標點符號。例如,“Concurrent hash maps”(併發雜湊對映)以駝峰式編寫為 -

ConcurrentHashMaps

我們可以用下列方法實現一個方法,在 JavaScript 中接受一個字串,並將其轉換為駝峰式 -

示例

function camelize(str) {
   // Split the string at all space characters
   return str.split(' ')
      // get rid of any extra spaces using trim
      .map(a => a.trim())
      // Convert first char to upper case for each word
      .map(a => a[0].toUpperCase() + a.substring(1))
      // Join all the strings back together
      .join("")
}
console.log(camelize("Concurrent hash maps"))

輸出

ConcurrentHashMaps

更新時間:19-9-2019

1K+ 瀏覽次數

開啟你的 事業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.