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

String Interpolation (Nội suy chuỗi) trong JavaScript

ES6 giới thiệu **Template Literals** (backtick ` `) — hỗ trợ interpolation native.

Cú pháp

var greeting = `Hello World!`;

Placeholder: ${expression}

var name = "Brendan";
console.log(`Hello, ${name}!`); // "Hello, Brendan!"

Expression trong placeholder

var a = 10, b = 10;
console.log(`The sum of ${a} and ${b} is ${a+b}`); // "The sum of 10 and 10 is 20"

Function call trong placeholder

function fn() { return "Hello World"; }
console.log(`Message: ${fn()} !!`); // "Message: Hello World !!"

Multi-line string

var multiLine = `
  This is
  a string
  with multiple
  lines`;
console.log(multiLine);

Tagged Template (nâng cao)

function tag(strings, ...values) { ... }
tag`Hello ${name}!`;

Lưu ý: Không dùng '${}' (single quote) — chỉ backtick mới hoạt động.