🍇
テンプレートリテラル (Template literals) メモ
バッククォート (`) で囲んだ文字列をテンプレートリテラルという。
`aaa bbb ccc` // バッククォート (`) で囲んでいる
myTag'xxx'
タグ付きテンプレートmyTag`This ${fruit} is ${color}.`;
上記の構文では、myTag
という関数を呼び出している。中身は以下の通り。
const fruit = "apple";
const color = 'red';
function myTag(strings, fruitExp, colorExp) {
console.log(`string[0] is ${strings[0]}`)
const str0 = strings[0]; // "This "
const str1 = strings[1]; // " is "
const str2 = strings[2]; // "."
return `${str0}${fruitExp}${str1}${colorExp}${str2}`;
}
const output = myTag`This ${fruit} is ${color}.`;
console.log(output); // "This apple is red."
- mdn参考 - Tagged templates
Discussion