Học cách thay thế tất cả instance của một từ (string) trong JavaScript dùng regular expressions (RegEx) và phương thức replace().
Giả sử bạn có khối text lớn nói về sản phẩm mới công ty, nhưng từ bị sai chính tả nhiều lần. Text block sau nên viết "Epic Games" không phải "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."
May mắn thay, sửa nhanh với 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."
Tuyệt!
Điều gì xảy ra trong code?
- Khai báo biến mới
textBlockCorrected. - Gán biến mới bằng giá trị
textBlockgốc. - Gắn
replace()chotextBlock, truyền argument regular expression:/Glorious/g, "Epic"— nơi phép màu xảy ra.
Cờ g (global) cho phép thay thế tất cả instance "Glorious" thành "Epic" trong text block. Cờ g là cách DUY NHẤT thay thế nhiều instance từ trong chuỗi, trong JavaScript.