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

Cách thay thế tất cả lần xuất hiện của chuỗi trong JavaScript

Để 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ó g chỉ 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ứcHỗ trợ regexCase-insensitiveThay thế động (function)Hỗ trợ trình duyệt
replaceAll(str, repl)KhôngKhông (cần tự lower)KhôngES2021+ (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ôngKhôngTất cả

Lưu ý quan trọng

  • String immutable: replace/replaceAll trả về chuỗi mới, KHÔNG sửa chuỗi gốc.
  • replaceAll vớ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 replace với string động:
    
    function escapeRegex(str) {
      return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    const userInput = "a.b";
    str.replace(new RegExp(escapeRegex(userInput), "g"), "X");
    
  • Performance: replaceAll nhanh 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."