สมมติว่าเราต้องเขียนฟังก์ชัน เช่น translate() ที่รับสตริงเป็นอาร์กิวเมนต์แรก และคำ bấtจำนวนหลังจากนั้น
สตริงจะมีเครื่องหมาย $ n ตัวแบบนี้ −
This $0 is more $1 just a $2. แล้วจะมี 3 สตริงที่จะแทนที่ตำแหน่งที่สอดคล้อง
ตัวอย่าง −
ถ้าการเรียกฟังก์ชันแบบนี้ −
translate('This $0 is more $1 just a $2.', 'game', 'than', 'game');ผลลัพธ์ของฟังก์ชันควรเป็น −
This game is more than just a game.
ฟังก์ชันนี้คล้ายกับ template injecting ใน JavaScript
ดังนั้น มาเขียนโค้ดสำหรับฟังก์ชันนี้
เราจะใช้ String.prototype.replace() ที่นี่ เรารู้ว่าถ้าเราใช้ regex pattern เพื่อจับคู่ทุกครั้งและใช้ฟังก์ชันเป็นพารามิเตอร์ที่สอง มันจะถูก execute สำหรับแต่ละ match เราจะทำเหมือนกันที่นี่
โค้ดสำหรับทำนี้จะเป็น −
ตัวอย่าง
const str = 'This $0 is more $1 just a $2'; const translate = (str, ...texts) => { const regex = /\$(\d+)/gi; return str.replace(regex, (item, index) => { return texts[index]; }); }; console.log(translate(str, 'game', 'just', 'game'));ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
This game is more just just a game