使用 JavaScript 將字串分解為固定長度的塊並刪除空格


問題

我們需要編寫一個 JavaScript 函式,該函式以一個可能包含空格的字串句子作為第一個引數,並以一個數字作為第二個引數。

我們的函式應首先刪除字串中的所有空格,然後將字串分解為由第二個引數指定數量的塊。

所有字串塊應具有相同的長度,但最後一部分除外,在某些情況下,最後一部分可能有不同的長度。

例子

以下為程式碼 −

 即時演示

const num = 5;
const str = 'This is an example string';
const splitString = (str = '', num = 1) => {
   str = str.replace(/\s/g,'');
   const arr = [];
   for(let i = 0; i < str.length; i += num){
      arr.push(str.slice(i,i + num));
   };
   return arr;
};
console.log(splitString(str, num));

輸出

[ 'Thisi', 'sanex', 'ample', 'strin', 'g' ]

更新於:2021-04-20

207 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.