用空格替代 JavaScript 中以 0 開頭的數字


我們需要編寫一個 JavaScript 函式,該函式接收一個表示數字的字串。

用空格替換數字中的前導零。請確保保留數字中的前導空格。

例如:如果字串值定義如下 −

"004590808"

則輸出應該是 −

"4590808"

示例

程式碼如下 −

const str = ' 004590808';
const replaceWithSpace = str => {
   let replaced = '';
   const regex = new RegExp(/^\s*0+/);
   replaced = str.replace(regex, el => {
      const { length } = el;
      return ' '.repeat(length);
   });
   return replaced;
};
console.log(replaceWithSpace(str));

輸出

控制檯中的輸出為 −

4590808

更新日期:22-Oct-2020

338 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.