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

Ký tự thoát (Escape Characters) trong JavaScript

Escape Sequences trong String

Ký tự thoát (escape sequence) cho phép biểu diễn các ký tự đặc biệt trong string literal. Bắt đầu bằng backslash (\\).

Bảng các escape sequence phổ biến

Mã Ký tự Mô tả
\bBackspaceXóa lùi 1 ký tự
\fForm FeedTrang mới (máy in)
\nNew LineXuống dòng (LF)
\rCarriage ReturnVề đầu dòng (CR)
\tTabTab ngang
\vVertical TabTab dọc
\'Single QuoteNháy đơn trong string nháy đơn
\"Double QuoteNháy kép trong string nháy kép
\\BackslashDấu \ chính
\xHHHex 2 chữ sốVD: \x41 = 'A'
\uHHHHUnicode 4 chữ sốVD: \u0041 = 'A'
\u{HHHHH}Unicode ES6VD: \u{1F600} = 😀

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>Escape Characters</title>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
        .result { font-size: 18px; font-weight: 500; font-family: monospace; white-space: pre-wrap; }
        .demo { background: #f5f5f5; padding: 15px; border-radius: 4px; margin: 10px 0; }
    </style>
</head>
<body>
    <h1>Escape Characters trong JavaScript</h1>
    <div class="result" id="result"></div>

    <script>
        const resEle = document.getElementById("result");
        
        // Chuỗi chứa nhiều escape sequence
        const str = 'Hello World "This" is some sample \\ Text \' ';
        
        resEle.textContent = 'Code: \'Hello World "This" is some sample \\\\ Text \\\' \'\n\n';
        resEle.textContent += 'Kết quả hiển thị:\n' + str + '\n\n';
        resEle.textContent += 'Các escape sequence phổ biến:\n';
        resEle.textContent += 'Dòng 1\\nDòng 2 (newline)\n';
        resEle.textContent += 'Cột 1\\tCột 2\\tCột 3 (tab)\n';
        resEle.textContent += 'Unicode: \\u0041 = A, \\u{1F600} = 😀\n';
        resEle.textContent += 'Hex: \\x41 = A';
    </script>
</body>
</html>

Escape trong Template Literals

// Template literal cũng dùng backslash
const str = `Line 1\nLine 2\tTab`;

// Nhưng KHÔNG cần escape quote
const quote = `He said "Hello" and 'Hi'`; // OK

// Cần escape backtick và ${}
const backtick = `\`Backtick\``;
const dollar = `\${notInterpolated}`; // Hiển thị ${notInterpolated}

Raw Strings - Không xử lý escape

// String.raw tag function
console.log(String.raw`Line1\nLine2`); 
// "Line1\\nLine2" (ký tự \ và n thực sự)

// Regex không cần double escape
const regex = String.raw`\d+\.\d+`; // Thay vì "\\d+\\.\\d+"

// Windows path
const path = String.raw`C:\Users\Name\Documents`;

Lưu ý quan trọng

  • Trong **string literal**, \ luôn là escape. Muốn in ra \ phải viết \\.
  • \' chỉ cần trong string nháy đơn '...'. Trong "..." không cần.
  • \" chỉ cần trong string nháy kép "...". Trong '...' không cần.
  • Template literal \`...\` cần escape \` và ${}.