破壞 JavaScript 中的駝峰式語法


問題

我們需要編寫一個 JavaScript 函式,該函式將一個 camelCase 字串 str 作為第一個且唯一的引數輸入。

我們的函式應構建並返回一個新的字串,該字串使用單詞之間的空格拆分輸入字串。

例如,如果對該函式的輸入為 -

輸入

const str = 'thisIsACamelCasedString';

輸出

const output = 'this Is A Camel Cased String';

示例

以下為程式碼 -

 即時演示

const str = 'thisIsACamelCasedString';
const breakCamelCase = (str = '') => {
   const isUpper = (char = '') => char.toLowerCase() !==
char.toUpperCase() && char === char.toUpperCase();
   let res = '';
   const { length: len } = str;
   for(let i = 0; i < len; i++){
      const el = str[i];
      if(isUpper(el) && i !== 0){
         res += ` ${el}`;
         continue;
      };
      res += el;
   };
   return res;
};
console.log(breakCamelCase(str));

輸出

this Is A Camel Cased String

更新時間:04-22-2021

189 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告