JavaScript String Templates
คำเทคความ:
- Template Literals
- Template Strings
- String Templates
วรรค์ในข้อความ
ด้วยการใชַ้,คุณสามารถใช้อักษรวรรค์และวรรค์สองบรรทัดในข้อความได้:
ตัวอย่าง
let text = `He's often called "Johnny"`;
ข้อความสองบรรทัด
ַอนุญาตให้มีข้อความสองบรรทัดขึ้นไป:
ตัวอย่าง
let text = ``The quick brown fox jumps over the lazy dog`;
interpolation
ַเปิดโอกาสให้ใส่ตัวแปรและเครื่องหมายเชิงพนันเข้าไปในข้อความโดยง่าย
วิธีนี้เรียกว่า string interpolation (string interpolation).
การเขียน
${...}
การแทนที่ความหมายตัวแปร
ַอนุญาตให้มีตัวแปรในข้อความ:
ตัวอย่าง
let firstName = "Bill"; let lastName = "Gates"; let text = `Welcome ${firstName}, ${lastName}!`;
การแทนที่ความหมายด้วยค่าที่แท้จริงของตัวแปรเรียกว่าstring interpolation
การแทนที่ความหมาย
ַอนุญาตให้มีเครื่องหมายเชิงพนันในข้อความ:
ตัวอย่าง
let price = 10; let VAT = 0.25; let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;
การแทนที่ความหมายด้วยค่าที่แท้จริงอัตโนมัติของข้อความเรียกว่า string interpolation。
HTML โมดูล
ตัวอย่าง
let header = "Templates Literals"; let tags = ["template literals", "javascript", "es6"]; let html = `<h2>${header}</h2><ul>`; for (const x of tags) { html += `<li>${x}</li>`; } html += `</ul>`;
ǰ
Internet Explorer ַ֧
һЩȫַֹ֧ıĶȿ汾
Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome 41 | Edge 13 | Firefox 34 | Safari 10 | Opera 29 |
2015 3 | 2015 11 | 2014 12 | 2016 9 | 2015 4 |