Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách Thay Thế Bất Kỳ Ký Tự Nào Bên Trong Chuỗi Với JavaScript

Học cách thay thế bất kỳ ký tự nào bên trong (string) với JavaScript dùng regular expressions (RegEx) và phương thức replace().

Giả sử bạn có khối text dùng em dash (—), nhưng nhầm dùng 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."

May mắn thay, sửa được với JS dùng regular expression và replace():

const textBlockCorrected = textBlock.replace(/-/g, "—") console.log(textBlockCorrected) // "When you're typing fast it's normal to make a few spelling mistakes here and there — it just means you're human."

Trông giống nhau? Tin tôi, không. Nhìn kỹ hơn. Hoặc in kết quả textBlock và textBlockCorrected dễ thấy khác biệt:

console.log(textBlock) //"When you're typing fast it's normal to make a few spelling mistakes here and there - it just means you're human." console.log(textBlockCorrected) // "When you're typing fast it's normal to make a few spelling mistakes here and there — it just means you're human."

Lưu ý: trong typography, dễ phân biệt chữ và ký hiệu hơn khi font không phải monotype như font code (font Menlo). Chi tiết về em, en, hyphen để hướng dẫn typography khác.