將連字元字串轉換為 JavaScript 中的駝峰式字串


假設我們有一個包含單詞的字串,這些單詞用連字元分隔,如下所示 −

const str = 'this-is-an-example';

我們需要編寫一個 JavaScript 函式,將此類字串作為輸入並將其轉換為駝峰式字串。

對於上面的字串,輸出應該是 −

const output = 'thisIsAnExample';

其程式碼如下 −

const str = 'this-is-an-example';
const changeToCamel = str => {
   let newStr = '';
   newStr = str
   .split('-')
   .map((el, ind) => {
      return ind && el.length ? el[0].toUpperCase() + el.substring(1)
      : el;
   })
   .join('');
   return newStr;
};
console.log(changeToCamel(str));

以下是控制檯上的輸出 −

thisIsAnExample

更新於: 09/10/2020

161 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

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