เราต้องเขียนฟังก์ชันที่รับสตริงแทนตัวเลข แทนที่ศูนย์นำหน้า (leading zeros) ด้วยช่องว่าง พร้อมรักษาช่องว่างเดิมไว้
ตัวอย่าง สตริง " 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