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

Template String (Template Literal) trong JavaScript


Template literal (backtick `) cho phép nhúng biểu thức ${expression}, xuống dòng tự do, không cần concat chuỗi. Hỗ trợ tagged template cho xử lý nâng cao.

Ví dụ

Format chuỗi với object personObj:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Template String JS</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result, .sample { font-size: 20px; font-weight: 500; color: blueviolet; }
    .sample { color: red; }
  </style>
</head>
<body>
  <h1>Template String (Template Literal) trong JavaScript</h1>
  <div class="sample">`Tên: ${personObj.name}, Tuổi: ${personObj.age}, Mã: ${personObj.rollno}`</div>
  <div class="result"></div>
  <br />
  <button class="Btn">FORMAT CHUỖI</button>
  <h3>Nhấn nút để xem template string được format với dữ liệu object</h3>
  <script>
    const btn = document.querySelector('.Btn');
    const resEle = document.querySelector('.result');
    const personObj = { name: 'Rohan Sharma', age: 12, rollno: 22 };
    btn.addEventListener('click', () => {
      resEle.innerHTML = `Tên: ${personObj.name}, Tuổi: ${personObj.age}, Mã: ${personObj.rollno}`;
    });
  </script>
</body>
</html>

Kết quả

Hiển thị: Tên: Rohan Sharma, Tuổi: 12, Mã: 22.

Mẹo: Dùng cho SQL query, HTML template, log message. Tagged template: sql`SELECT * FROM users WHERE id = ${id}` tự escape SQL injection.