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

แทนที่ Character ใดๆ ใน String ด้วย JavaScript (RegEx + replace)

เรียนรู้แทนที่ character ใดๆ ใน string ด้วย Regular Expressions (RegEx) และเมธอด replace()

สมมติ text block ควรใช้ em dash (—) แต่พิมพ์ hyphen (-) ติด:

const textBlock = "When you're typing fast it's normal to make a few spelling mistakes here and there - it just means you're human."

แก้ด้วย regex และ replace():

const textBlockCorrected = textBlock.replace(/-/g, "—");
console.log(textBlockCorrected);
// "When you're typing fast... there — it just means you're human."

ดูเหมือนกัน? ใกล้เคียง แต่ต่างกัน ลอง print ทั้งคู่:

console.log(textBlock); // ... there - it just...
console.log(textBlockCorrected); // ... there — it just...

Note: ใน typography em dash vs hyphen แยกง่ายกว่านี้ถ้า font ไม่ใช่ monotype (code font = Menlo) เรื่อง em, en, hyphen จะอธิบายใน typography tutorial แยก