在 JavaScript 中修剪和拆分字串以形成陣列


假設我們有一個這樣的逗號分隔字串 -

const str = "a, b, c, d , e";

我們需要編寫一個 JavaScript 函式,該函式接收一個此類函式並將其中包含的所有空格都刪除掉。

然後,我們的函式應將字串拆分為形式文獻的陣列並返回該陣列。

示例

對此的程式碼將是 -

const str = "a, b, c, d , e";
const shedAndSplit = (str = '') => {
   const removeSpaces = () => {
      let res = '';
      for(let i = 0; i < str.length; i++){
         const el = str[i];
         if(el === ' '){
            continue;
         };
         res += el;
      };
      return res;
   };
   const res = removeSpaces();
   return res.split(',');
};
console.log(shedAndSplit(str));

輸出

並且控制檯中的輸出將是 -

[ 'a', 'b', 'c', 'd', 'e' ]

更新於: 23-Nov-2020

806 次瀏覽

開啟您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.