Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

วิธีการแทนที่อินสแตนซ์ทั้งหมดของสตริงด้วย JavaScript

เรียนรู้วิธีแทนที่คำ (สตริง) ทุกคำใน JavaScript โดยใช้นิพจน์ทั่วไป (RegEx) และ replace() วิธีการ

สมมติว่าคุณมีกลุ่มข้อความจำนวนมากที่พูดถึงผลิตภัณฑ์ล่าสุดของบริษัทของคุณ แต่น่าเสียดาย ที่สะกดผิดคำหนึ่งคำหลายครั้ง บล็อกข้อความต่อไปนี้ควรจะพูดว่า "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."

โชคดีที่เราแก้ไขได้ด้วย JavaScript อย่างรวดเร็ว

const textBlockCorrected = textBlock.replace(/Glorious/g, "Epic")

console.log(textBlockCorrected)
// "We at Epic Games, are very proud to present the latest edition of the Unreal Tournament series. Epic Games would like to invite our fans to come over to the Epic Games stand at E3 in 2021."

เย้!

เกิดอะไรขึ้นในโค้ดนี้

  • ขั้นแรก เราประกาศตัวแปรใหม่ชื่อ textBlockCorrected .
  • จากนั้นเราตั้งค่าตัวแปรใหม่นั้นเท่ากับค่าของ textBlock ดั้งเดิม .
  • จากนั้นเราแนบ replace() วิธีการ textBlock และให้อาร์กิวเมนต์ของนิพจน์ทั่วไปนี้แก่มัน:/Glorious/g, "Epic" ซึ่งเป็นที่ที่เวทมนตร์เกิดขึ้น

g (ทั่วโลก) แฟล็กคือสิ่งที่ช่วยให้เราสามารถแทนที่อินสแตนซ์ทั้งหมดของ "Glorious" ด้วย "Epic" ในบล็อกข้อความ g ธงเป็นวิธีเดียวที่จะแทนที่อินสแตนซ์ของคำหลายคำในสตริงใน JavaScript