Template Literals (hay Template String) hiểu đơn giản là ta thay thế các ký tự trong chuỗi thành một biến nào đó có thể chỉnh sửa.

Ví dụ:

console.log(`The sum of 2 and 3 is 5`) // statically writing the data

Có thể dùng template literals như sau:

let a = 2
let b = 3
 
console.log(`The sum of ${a} and ${b} is ${a + b}`) // injecting the data dynamically

Important

Chú ý là ta sử dụng dấu backtick `` để chứa chuỗi có template literals.

Ví dụ dưới đây có thể minh họa cho sự tiện lợi của việc sử dụng template literals. Mỗi lần ta cần thay đổi nội dung của chuỗi, ta chỉ cần thay giá trị của biến.

let firstName = "Lê Minh"
let lastName = "Qbu"
let country = "VietNam"
let city = "HCM"
let language = "JavaScript"
let job = "student"
let age = 20
let fullName = firstName + " " + lastName
 
let personInfoTwo = `I am ${fullName}. I am ${age}. I live in ${country}.` //ES6 - String interpolation method
let personInfoThree = `I am ${fullName}. I live in ${city}, ${country}. I am a ${job}. I teach ${language}.`
 
console.log(personInfoTwo)
console.log(personInfoThree)

Thậm chí ta còn có thể thêm các biểu thức vào chuỗi thông qua template literals:

let a = 2
let b = 3
 
console.log(`${a} is greater than ${b}: ${a > b}`)

Tip

Sử dụng toán tử [] để truy cập ký tự trong chuỗi. Sử dụng thuộc tính length để lấy ra độ dài chuỗi.