Để thay thế tất cả lần xuất hiện của một chuỗi con, dùng phương thức replaceAll() (ES2021) hoặc replace() với regex global flag /g.
1. replaceAll() - ES2021 (Khuyến nghị, đơn giản nhất)
const str = "John loves studying. He loves Football too!";
const result = str.replaceAll("loves", "likes");
console.log(result);
// "John likes studying. He likes Football too!"
- Tham số 1: chuỗi tìm kiếm (string) – KHÔNG phải regex.
- Tham số 2: chuỗi thay thế.
- Case-sensitive.
2. replace() với Regex global flag /g (Cổ điển, linh hoạt)
const str = "John loves studying. He loves Football too!";
const result = str.replace(/loves/g, "likes");
console.log(result);
// "John likes studying. He likes Football too!"
- Regex
/loves/g:g= global (tất cả), không cógchỉ thay lần đầu. - Hỗ trợ pattern phức tạp:
/love/gi(case-insensitive),/\bcat\b/g(whole word).
3. Regex với function replacement (Nâng cao)
// Viết hoa từ đầu mỗi từ
"hello world".replace(/\b\w/g, m => m.toUpperCase()); // "Hello World"
// Thay thế có điều kiện
"a1b2c3".replace(/\d/g, d => parseInt(d) * 2); // "a2b4c6"
// Sử dụng groups
"2024-01-15".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1"); // "15/01/2024"
So sánh
| Phương thức | Hỗ trợ regex | Case-insensitive | Thay thế động (function) | Hỗ trợ trình duyệt |
|---|---|---|---|---|
replaceAll(str, repl) | Không | Không (cần tự lower) | Không | ES2021+ (Chrome 85+, FF 77+, Safari 13.1+) |
replace(regex, repl) | Có | Có (flag i) | Có | Tất cả (ES1) |
replace(str, repl) | Không (chỉ lần đầu) | Không | Không | Tất cả |
Lưu ý quan trọng
- String immutable:
replace/replaceAlltrả về chuỗi mới, KHÔNG sửa chuỗi gốc. replaceAllvới regex sẽ báo lỗi:str.replaceAll(/abc/g, "x")→ TypeError. Chỉ nhận string.- Escape regex special chars nếu dùng
replacevới string động:function escapeRegex(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } const userInput = "a.b"; str.replace(new RegExp(escapeRegex(userInput), "g"), "X"); - Performance:
replaceAllnhanh hơn regex cho replace đơn giản.
Ví dụ thực tế
// Sanitize input: bỏ tất cả ký tự không phải chữ/số
const sanitized = input.replaceAll(/[^a-zA-Z0-9]/g, ""); // ❌ Sai - replaceAll không nhận regex
const sanitized = input.replace(/[^a-zA-Z0-9]/g, ""); // ✅ Đúng
// Template đơn giản
const template = "Chào {name}, bạn có {count} tin nhắn.";
const result = template
.replaceAll("{name}", "An")
.replaceAll("{count}", "5");
// "Chào An, bạn có 5 tin nhắn."