JavaScript ตั้งแต่ ES6 มี template string support ให้ native string interpolation เรียกว่า template literals Template literals คือ string literals ที่ allow embedded expressions ใช้ back-ticks (`) แทน single/double quotes
var greeting = `Hello World!`;
Template strings ใช้ placeholders สำหรับ string substitution ด้วย syntax ${ }
ตัวอย่าง 1
var name = "Brendan"; console.log('Hello, ${name}!');ผลลัพธ์
Hello, Brendan!
ตัวอย่าง 2
Template literals และ expressions
var a = 10; var b = 10; console.log(`The sum of ${a} and ${b} is ${a+b} `);ผลลัพธ์
The sum of 10 and 10 is 20
ตัวอย่าง 3
Template literals และ function expression
function fn() { return "Hello World"; } console.log(`Message: ${fn()} !!`);ผลลัพธ์
Message: Hello World !!
Template strings รองรับ multiple lines
ตัวอย่าง
var multiLine = ` This is a string with multiple lines`; console.log(multiLine)
ผลลัพธ์
This is a string with multiple line