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

Template Strings (Template Literals) trong JavaScript

Template Literals (ES2015/ES6)

Template literals dùng **backtick (\`)** thay cho nháy đơn/kéo, cho phép:

  • Interpolation (nội suy): Nhúng biểu thức ${expression}.
  • Multi-line: Xuống dòng tự nhiên không cần \n.
  • Tagged templates: Xử lý tùy chỉnh với hàm tag.

Ví dụ minh họa

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Template Strings</title>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
        .result { font-size: 20px; font-weight: 500; color: blueviolet; font-family: monospace; }
        button { padding: 8px 16px; cursor: pointer; }
    </style>
</head>
<body>
    <h1>Template Strings trong JavaScript</h1>
    <div class="result"></div>
    <button class="btn-demo">HIỂN THỊ KẾT QUẢ</button>
    <h3>Nhấn nút để cộng 2 số và hiển thị với template string</h3>

    <script>
        const resEle = document.querySelector(".result");
        const btn = document.querySelector(".btn-demo");

        const a = 22;
        const b = 44;

        function add(a, b) {
            return a + b;
        }

        btn.addEventListener("click", () => {
            // Template literal với interpolation
            resEle.textContent = `Tổng của ${a} và ${b} = ${add(a, b)}`;
            
            // Demo multi-line
            resEle.textContent += `\n\nMulti-line:\nDòng 1\nDòng 2\nDòng 3`;
        });
    </script>
</body>
</html>

So sánh: Trước và sau ES6

// Trước ES6 (concatenation)
var a = 22, b = 44;
var msg = 'Tổng của ' + a + ' và ' + b + ' = ' + (a + b);
// "Tổng của 22 và 44 = 66"

// ES6 Template Literal
const msg = `Tổng của ${a} và ${b} = ${a + b}`;
// "Tổng của 22 và 44 = 66"

// Multi-line trước ES6
var html = '
\n Hello\n
'; // ES6 const html = `
Hello
`;

Tagged Templates (Nâng cao)

Hàm tag nhận: mảng các chuỗi tĩnh, và các giá trị interpolated.

function highlight(strings, ...values) {
    return strings.reduce((result, str, i) => {
        return result + str + (values[i] ? `${values[i]}` : '');
    }, '');
}

const name = 'John';
const age = 30;
const message = highlight`Tên: ${name}, Tuổi: ${age}`;
// "Tên: John, Tuổi: 30"

// Thư viện thực tế: styled-components, graphql-tag

Raw Strings (String.raw)

// String.raw bỏ qua escape sequences
console.log(`Line1\nLine2`);      // Line1 (xuống dòng) Line2
console.log(String.raw`Line1\nLine2`); // "Line1\\nLine2" (chữ \n)

// Dùng cho regex, path Windows
const regex = String.raw`\d+\.\d+`;
const path = String.raw`C:\Users\Name`;

Best Practices

  1. Dùng template literals cho **string concatenation** phức tạp.
  2. Dùng cho **multi-line strings** (HTML, SQL, text).
  3. Tránh lạm dụng tagged templates trừ khi build DSL/thư viện.
  4. Nhớ escape backtick trong template: \`.