Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การจัดรูปแบบสตริงตามแพทเทิร์น (Masking) ใน JavaScript

เราต้องเขียนฟังก์ชันที่รับสตริงและแพทเทิร์น (pattern) แล้วเติมตัวอักษรของสตริงเข้าไปในตำแหน่งของ '#' ในแพทเทิร์น

ตัวอย่าง: สตริง '123456789' และแพทเทิร์น '## ## ## ###' ผลลัพธ์ควรเป็น '12 34 56 789'

ตัวอย่างโค้ด

const str = '123456789';
const pattern = '## ## ## ###';

const maskString = (str, pattern) => {
  let i = 0;
  const padded = pattern.replace(/#/g, () => {
    return str[i++];
  });
  return padded;
};

console.log(maskString(str, pattern));

ผลลัพธ์

ค่าที่แสดงในคอนโซลจะเป็นดังนี้:

12 34 56 789