เรียนรู้แทนที่ทุก instance ของคำ (string) ใน JS ด้วย RegEx และ replace()
Text block ใหญ่พูดถึงผลิตภัณฑ์ใหม่ แต่มีคำผิดหลายครั้ง ควรเป็น "Epic Games" ไม่ใช่ "Glorious Games":
const textBlock = "We at Glorious Games, are very proud to present the latest edition of the Unreal Tournament series. Glorious Games would like to invite our fans to come over to the Glorious Games stand at E3 in 2021."
แก้ไขได้เร็ว:
const textBlockCorrected = textBlock.replace(/Glorious/g, "Epic");
console.log(textBlockCorrected);
// "We at Epic Games, are very proud... Epic Games would like to invite... Epic Games stand at E3 in 2021."
อธิบายโค้ด:
- Declare
textBlockCorrected - Set =
textBlockvalue - Attach
replace()argument regex:/Glorious/g, "Epic"— ที่นี่คือ magic
Flag g (global) คือกุญแจที่ replace ทุก "Glorious" ด้วย "Epic" ใน text block — วิธีเดียว ที่ replace multiple instances ใน string ได้ใน JS