用 JavaScript 將任何字串轉換為駝峰式,同時刪除空格


要將字串轉換為駝峰式,你需要將單詞的首字母小寫,而其他單詞的首字母必須大寫。

以下是將任何字串轉換為駝峰式的程式碼 -

示例

function convertStringToCamelCase(sentence) {
   return sentence.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g,
   function(camelCaseMatch, i) {
      if (+camelCaseMatch === 0)
         return "";
      return i === 0 ? camelCaseMatch.toLowerCase() :
      camelCaseMatch.toUpperCase();
   });
}
console.log(convertStringToCamelCase("Add two variables"));

要執行以上程式,你需要使用以下命令 -

node fileName.js.

此處,我的檔名是 demo104.js。

輸出

這將產生以下輸出 -

PS C:\Users\Amit\JavaScript-code> node demo104.js
addTwoVariables

更新於:2020 年 9 月 7 日

919 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.