用空格替代 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP